At Wed, 6 Sep 2000 00:29:21 +0900,
Dave Thomas <Dave / thomases.com> wrote:

> > Can somebody please explain what a closure is within the context of
> > Ruby? (Simple explanation, simple example).
> 
> A closure is simply a chunk of code that "remembers" the context that
> it originally appeared in. This is unusual, because in conventional
> block-structured languages, once something goes out of scope it is
> lost.

Dave has already explained closure nicely, so I'll show a pitfall.

As Dave stated, a closure remembers the context that a chunk of code
"originally" appeared in.


a = 1 obj = Proc.new { print "scope B: ", a, "\n" } print "scope A: ", a, "\n" obj.call a = 20 obj.call $ ruby proc.rb scope A: 1 scope B: 1 scope B: 20
The code above showed that Proc'ed block remebered 'original' context, rather than remembering the value of 'a' at the block which is 1. In the above example the scope of the variable 'a' is in toplevel, therefore it's not out of scope after the block. If it's out of scope, assign to variable 'a' doesn't, of cause, affect.
def foo(a) proc { print "scope B: ", a, "\n" } end obj = foo(1) obj.call a = 20 # first appearance of 'a' in this scope obj.call # so it doesn't affect variable 'a' in the block $ ruby proc_out.rb scope B: 1 scope B: 1
hope this helps, -- yashi