O'Reilly logo

Mastering Ruby Closures by Benjamin Tan Wei Hao

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required