Blocks as Closures and Block Local Variables

In Ruby, blocks act like anonymous functions. After all, blocks carry a bunch of code, to be called only when yielded. A block also carries around the context in which it was defined:

 def​ chalkboard_gag(line, repetition)
  repetition.times { |x| puts ​"​​#{​x​}​​: ​​#{​line​}​​"​ }
 end
 
 chalkboard_gag(​"I will not drive the principal's car"​, 3)

This returns:

 0: I will not drive the principal's car
 1: I will not drive the principal's car
 2: I will not drive the principal's car

What’s the free variable here? It is line. That’s because line is not a block local variable. Instead, it needs access to the outer scope until it reaches the arguments of chalkboard_gag.

The behavior of the ...

Get Mastering Ruby Closures now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.