>>>>> "Steve" == Steve Merrick <Steve.Merrick / Marconi.com> writes:

    Steve> "Stuart Zakon" <zakons / objectsbydesign.com> wrote in
    Steve> message news:8p2raa$fbq$1 / nnrp1.deja.com...
    >> Can somebody please explain what a closure is within the
    >> context of Ruby? (Simple explanation, simple example).

    Steve> I too would be grateful for such an explanation. "Closure"
    Steve> has become trendy in recent years, but I'm humble enough
    Steve> (not really! ;-) to admit I haven't a clue what it is. ;-}

Hmmm ... it something everybody knows but difficult to explain ;-) Let
me try:

I would explain a closure as a piece of code that happens to remember
the whole context it was created in! In opposition to functions/
methods (which establish a context or work in a context established by 
others), a closure works only in its birth context.

In a class a method works in a context created by the constructor. A
subroutine works in a context created by itself. 

In Ruby a context is a part of code surrounded via '{' ... '}' or 'do' 
... 'end'. Look at this:


  age = 12
  clos = proc { age += 1; puts "Inner age is #{age}" }
  clos.call
  puts "Outer age is #{age}"
  age = 36
  clos.call
  puts "Outer age is #{age}"
   
will gives us:

  Inner age is 13
  Outer age is 13
  Inner age is 37
  Outer age is 37

Here the closure is surrounded via '{' ... '}'. We use 'proc' to
make the closure an object we can deal with (e.g. assign it to
variable 'clos'). The variable 'age' is now tied together with the
closure. Changing it anywhere in the closure OR the surrounding
environment will be recognized at both places!

    Steve> -- Steve

HTH,
\cle