Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 37 ยท Collections and Blocks

Blocks, Procs and yield in Crystal

Learn Crystal blocks, yield, block arguments, &block capture, Proc literals, closures, return and next inside blocks, and inlining, with Ruby stand-ins.

A block is a chunk of code you hand to a method. It is the reason Crystal code reads so smoothly: list.each { |x| puts x }, File.open("a.txt") do |file| ... end, 3.times { ... }. Blocks look the same as in Ruby, but Crystal compiles them differently: when a method uses yield, the compiler inlines the block into the method, so a block call costs nothing at run time.

The Crystal listings below are read-only. The Ruby stand-ins run on the site and behave the same way for these examples.

yield

A method calls its block with yield. Any values after yield become the block's arguments, and the value of the block's last expression is the value of yield.

CRYSTAL
def twice
  yield
  yield
end

twice { puts "hello" }

def each_pair_sum(a : Array(Int32))
  a.each_cons(2) do |(x, y)|
    yield x + y
  end
end

each_pair_sum([1, 2, 3, 4]) { |sum| puts sum }   # 3, 5, 7

Unlike Ruby, where any method accepts a block silently, a Crystal method must contain yield (or capture the block) to use one. Calling a block-less method with a block is a compile error.

You can also give the block's parameter types:

CRYSTAL
def transform(value : Int32, &block : Int32 -> Int32)
  block.call(value)
end

transform(5) { |n| n * 10 }   # 50

The &block : Int32 -> Int32 syntax says "this block takes an Int32 and returns an Int32". Because the block is now a captured Proc, it can be stored, passed on or called later with .call. A method that only uses yield does not need a name for its block.

Ruby Ruby stand-in: yield and the block's value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Returning from blocks: next and break

Inside a block, next leaves the block early and gives yield a value, while break leaves the whole method that called the block. A return inside a block returns from the method that contains the block, which can surprise newcomers.

CRYSTAL
def first_even(list : Array(Int32)) : Int32?
  list.each do |n|
    return n if n.even?      # returns from first_even
  end
  nil
end

result = [1, 2, 3, 4].map do |n|
  next 0 if n.odd?           # this block returns 0 for odd numbers
  n * 10
end
# [0, 20, 0, 40]

found = [5, 6, 7].each do |n|
  break n if n > 5           # stops each; found == 6
end
Ruby Ruby stand-in: next, break and return

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Proc: a block you can keep

A Proc is an object that holds code. Create one with the arrow syntax or by capturing a block, store it in a variable or a collection, and run it with call.

CRYSTAL
add = ->(a : Int32, b : Int32) { a + b }
add.call(2, 3)                 # 5
add.call(2, 3)                 # procs are values

square = ->(x : Int32) { x * x }
[1, 2, 3].map(&square)         # [1, 4, 9]

handlers = [] of Proc(String, Nil)
handlers << ->(s : String) { puts "got #{s}" }
handlers.each { |h| h.call("event") }

# a pointer to an existing method
def shout(s : String) : String
  s.upcase
end
pointer = ->shout(String)      # Proc(String, String)
pointer.call("hi")             # "HI"

The type of add is Proc(Int32, Int32, Int32): the argument types first and the result type last. The &square in map(&square) passes a proc as the block. In the other direction, &.method is short block syntax: names.map(&.upcase) means names.map { |n| n.upcase }.

Closures

A block or proc closes over the variables it can see, even after the surrounding method has finished:

CRYSTAL
def make_counter
  count = 0
  -> { count += 1 }
end

next_id = make_counter
next_id.call   # 1
next_id.call   # 2
other = make_counter
other.call     # 1, its own count
Ruby Ruby stand-in: a closure that remembers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

How block inlining affects you

With yield, the block is not a heap object; the compiler pastes it into the method. This brings two practical consequences:

  • A block passed to a yield method cannot be stored in a variable (it is not an object), but it can use return, next and break freely.
  • A captured &block or a Proc literal is an object. It allocates and is called through a pointer, and a return inside a proc returns from the proc itself, not from the enclosing method.

Prefer plain yield for loops and callbacks you call right away. Reach for a Proc only when you need to keep the code for later, such as in an event table or a timer. You can also create a macro when even more flexibility is needed at compile time.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the value of yield equal?

    yield runs the block and evaluates to whatever the block's last expression produced.
  2. 2. Inside a block, what does break do?

    next leaves the block early; break stops the method that called the block, such as each.
  3. 3. What is the type of ->(a : Int32, b : Int32) { a + b }?

    A Proc type lists the argument types first and the return type last.
  4. 4. What does names.map(&.upcase) mean?

    &.method is short block syntax: it calls the method on each yielded value.

Summary

  • yield calls the block; its result is the block's last expression.
  • Methods using only yield have their block inlined: it is as fast as hand-written code.
  • next leaves the block, break leaves the calling method, return leaves the enclosing method.
  • A Proc is a storable closure with a type like Proc(Int32, Int32).
  • &.method is a short form of a block.

Next: Enumerable, Iterators and Lazy Pipelines