From: Robert Klemme Date: 2012-02-23T22:10:28+09:00 Subject: Re: How are closures implemented? On Mon, Feb 20, 2012 at 11:23 PM, Brian Candler wrote: > Ralph Shnelvar wrote in post #1047769: >> How are closures implemented?  How does the closure know about its >> environment? > > The closure *is* the environment. > > Are you familiar with local variables allocated on a stack? Then instead > imagine stack frames allocated out of the heap, in a linked list. > Instead of being deallocated at the end of a function, they are > garbage-collected when there are no more references to them, just like > any other object. This is the best explanation about closures I have read in a long time, Brian! Ralph, try this and see whether it helps the explanation sink in: def f(x) [ lambda { x += 1 }, lambda { x += 0.5 }, ] end a, b = f(0) 3.times do p a.call, b.call end Note how there is just a single environment which is shared by the two closures. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/