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

Get The Book of Ruby 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.