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.


x = "hello world"

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

def aMethod( aBlockArg )
   x = "goodbye"

puts( x )
aMethod( ablock )
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 "good-bye."

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