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 ) }# from w ww  .  j  a  va2 s  .  com

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