Ruby - Function Closure

What Is a Closure?

A closure is a function capturing (store or enclose) values of local variables within the scope in which the block was created.

Ruby's blocks are closures.

Demo

x = "hello world"

ablock = Proc.new { puts( x ) }# from w ww . ja  v a  2s .c  o m

def aMethod( aBlockArg )
   x = "goodbye"
   aBlockArg.call
end

puts( x )
ablock.call
aMethod( ablock )
ablock.call
puts( x )

Result

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 "good-bye."

In spite of that, when ablock is passed to aMethod and called within the scope of aMethod, it prints "hello world".