Blocks, yield and closures

yield and block_given?

Every method can be called with a block, and yield runs it. The method does not declare the block; it asks whether one was given and calls it:

def twice return :no_block unless block_given? yield yield end p(twice { puts "hi" }) p twice

ruby twice_demo.rb

hi
hi
nil
:no_block

yield returns the value of the block, so a method can collect it, compare it or pass it on. block_given? is the guard that keeps a method usable without a block.

The block as a named object

&block as the last parameter captures the block into a Proc, which is what a method needs when it wants to store the block or pass it to another call:

def run(&block) block.call end p(run { :done })

ruby -e 'def run(&block) = block.call; p(run { :done })'

:done

block.call and yield do the same thing here. The captured form is the one to use when the block is called later, stored in an object, or handed to map.

A block is a closure

A block keeps the local variables that were in scope where it was written, even after the method that defined them has returned:

ruby -e 'def counter; n = 0; -> { n += 1 }; end; c = counter; p c.call, c.call'

1
2

The lambda holds n, so the two calls see the same counter. That is the mechanism behind a memoised value, a lazy default, and the each block that reads a variable from outside the loop.

A with_timing helper

The pattern that uses everything above in four lines: take a block, run it, print how long it took. It is the helper a script reaches for before a profiler:

def with_timing started = Time.now yield puts (Time.now - started).round(1) end with_timing { sleep 0.1 }

ruby -e 'def t; s = Time.now; yield; puts (Time.now - s).round(1); end; t { sleep 0.1 }'

0.1

The number is the elapsed seconds as a float, rounded to one decimal: close to the one-tenth the block asked for, and steady enough to compare from one run to the next. Wrap the block around the suspicious step rather than the whole script; the section that takes the time is the one to read.

What to watch for

yield without a block and without a guard raises LocalJumpError. A method cannot give itself a default block, so guard with block_given? or capture the block as &block and call it with block&.call.

A block is not a method argument: return inside a block returns from the method that yielded, which surprises a reader who expects it to leave the block only. A lambda returns from itself, which is why a stored callback is usually a lambda.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. A method calls yield twice. What does the caller have to pass?

    Answer

    A block

    yield runs the block given at the call; the method does not declare it.

  2. What does this program print? def twice return :no_block unless block_given? yield yield end p(twice { puts "hi" }) p twice

    Answer

    hi / hi / nil / :no_block

    The guarded first call yields twice and answers nil; the second call returns :no_block.

  3. What does block_given? tell a method?

    Answer

    Whether a block was passed at this call

    It answers the presence of a block, which is what makes the guarded yield safe.

  4. What does this program print? def twice return :no_block unless block_given? yield yield end p twice

    Answer

    :no_block

    block_given? is false, so the guard returns :no_block before either yield runs.

  5. What does &block as the last parameter do?

    Answer

    Captures the block as a Proc the method can store or pass on

    yield cannot store the block; the & parameter gives it a name and an object.

  6. What does this program print? def run(&block) block.call end p(run { :done })

    Answer

    :done

    block.call runs the captured block, which is :done, and p prints that value.

  7. What does this program print? def counter n = 0 -> { n += 1 } end c = counter p c.call, c.call

    Answer

    1 / 2

    The lambda is a closure: it keeps n alive, and both calls see the same counter.

  8. What does yield return to the method?

    Answer

    The value of the block

    That is why a method can collect the block value, compare it or pass it on.

  9. What does this program raise? def twice yield end twice

    Answer

    LocalJumpError, because no block was given

    yield with no block and no guard raises LocalJumpError.

  10. How does return inside a block differ from return inside a lambda?

    Answer

    A block return leaves the method that yielded, a lambda return leaves the lambda

    A block is not a method of its own; a lambda is, which is why a stored callback is usually a lambda.

Article author: Arthur Isaev