July 2011
Intermediate to advanced
400 pages
8h 46m
English
A closure is a function that has the ability to store (that is, to “enclose”) values of local variables within the scope in which the block was created (think of this as the block’s “native scope”). Ruby’s blocks are closures. To understand this, look at this example:
block_closure.rb
x = "hello world"
ablock = Proc.new { puts( x ) }
def aMethod( aBlockArg )
x = "goodbye"
aBlockArg.call
end
puts( x )
ablock.call
aMethod( ablock )
ablock.call
puts( x )Here, the value of the local variable x is “hello world” within the scope of ablock. Inside aMethod, however, a local variable named x has the value “goodbye.” In spite of that, when ablock is passed to aMethod and called within the scope of aMethod, it prints “hello world” (that ...
Read now
Unlock full access