Blocks and Closures
Block Syntax
Section titled “Block Syntax”Both forms are equivalent:
# Brace form (conventionally single-line)[1, 2, 3].map { |x| x * 2 }
# do/end form (conventionally multi-line)[1, 2, 3].map do |x| x * 2endTyped Block Parameters
Section titled “Typed Block Parameters”Methods declare a typed block parameter with &block:
def map(&block: (T) -> R): Array[R]def each(&block: (T) -> Void): VoidReceiver Blocks
Section titled “Receiver Blocks”Receiver blocks allow self inside a block to be statically typed to a specific
receiver, enabling DSL patterns. The receiver type is declared with with:
def html(&block: () -> Void with HtmlBuilder): HtmlBuilder builder = HtmlBuilder.new yield builder builderendInvoking a Receiver Block
Section titled “Invoking a Receiver Block”yield is used to invoke the block. For receiver blocks, the first argument to yield
becomes self inside the block. Subsequent arguments are the block’s parameters.
# No block args — only a receiveryield builder
# Block args + receiver — receiver is always firstyield builder, itemThe type (A) -> B with C maps to: receiver C as self, argument A, return B.
def each_item(&block: (Item) -> Void with Context): Void ctx = Context.new @items.each do |item| yield ctx, item endendDSL Usage
Section titled “DSL Usage”page = html do # self is HtmlBuilder head do # self is HeadBuilder title "Hello" end body do # self is BodyBuilder p "World" endendLambdas
Section titled “Lambdas”Lambdas use the stabby arrow syntax:
double = ->(x: Int) { x * 2 }double = ->(x: Int): Int { x * 2 } # with explicit return typeLambdas and stored blocks share the same type — the function signature (T) -> R.
Call a stored lambda or block with .call:
fn = ->(x: Int) { x * 2 }fn.call(5) # 10Block Passing at Call Sites
Section titled “Block Passing at Call Sites”&variable
Section titled “&variable”A stored lambda can be passed as the block argument to a method using &:
double = ->(x: Int) { x * 2 }[1, 2, 3].map(&double) # same as .map { |x| x * 2 }The variable’s type must be compatible with the method’s &block parameter type.
A &block parameter received by a method can be passed on the same way:
def apply(items: Array[Int], &block: (Int) -> Int): Array[Int] items.map(&block)end&:symbol
Section titled “&:symbol”&:symbol is shorthand for a block that calls the named method on each element:
["alice", "bob"].map(&:upcase) # same as .map { |s| s.upcase }users.select(&:active?) # same as .select { |u| u.active? }The compiler resolves the method from the element type at compile time — if the method does not exist on that type, it is a compile error. Arguments cannot be passed with this shorthand; use a full block if arguments are needed.
&method(:name)
Section titled “&method(:name)”method(:name) captures a reference to a method as a callable value of the
appropriate function type:
def double(x: Int): Int x * 2end
[1, 2, 3].map(&method(:double)) # same as .map { |x| double(x) }Instance methods can be captured on a specific receiver:
[1, 2, 3].map(&formatter.method(:format))Return Semantics
Section titled “Return Semantics”Amethyst follows Ruby’s return semantics:
returninside a block returns from the enclosing methodreturninside a lambda (->) returns from the lambda itselfnextexits the current block iteration (local return from block)breakexits the method that yielded the block
| Keyword | Behaviour in a block | Mechanism |
|---|---|---|
return |
Returns from the enclosing method | ControlFlowReturnException |
next |
Returns from the block (local return) | Normal IL ret from the block |
break |
Exits the method that called yield |
ControlFlowBreakException |
Lambdas never throw control flow exceptions — return compiles to a normal IL ret.
Control Flow Exceptions
Section titled “Control Flow Exceptions”Non-local return and break from blocks are implemented via exceptions under the hood.
return valueinside a block compiles tothrow ControlFlowReturnException(target_id, value)break valueinside a block compiles tothrow ControlFlowBreakException(target_id, value)- Each method that uses
yieldis assigned a uniquetarget_idat compile time - The
yieldcall site wraps in a try/catch and only intercepts iftarget_idmatches, otherwise re-throws
This ensures correct behaviour with nested blocks:
def outer inner do return "hello" # targets outer's frame ID — passes through inner's yield uncaught endend
def inner(&block: () -> Void): Void yield # catches ControlFlowReturnException only if target_id matches inner — it doesn'tend