What Is a Closure?

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 is, the value of x within the block’s native scope) rather than “goodbye,” which is the value of x within the scope of aMethod. The previous code, therefore, only ever prints “hello world.”

Note

See Digging Deeper in Digging Deeper for more on closures.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.77.63