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 ) }#  w w w . java  2  s.c  om

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