From: Ralph Shnelvar Date: 2012-02-24T00:53:57+09:00 Subject: Re: How are closures implemented? Robert, Thursday, February 23, 2012, 6:10:28 AM, you wrote: RK> 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. RK> This is the best explanation about closures I have read in a long time, Brian! RK> Ralph, try this and see whether it helps the explanation sink in: RK> def f(x) RK> [ RK> lambda { x += 1 }, RK> lambda { x += 0.5 }, RK> ] RK> end RK> a, b = f(0) RK> 3.times do RK> p a.call, b.call RK> end RK> Note how there is just a single environment which is shared by the two closures. Ok ... modifying your example class Y z = 10 define_method :f do |x| [ lambda { z += z ; puts("z += z: z=#{z}, x=#{x}"); x }, lambda { x += 0.5; ; puts("x += 0.5: z=#{z}, x=#{x}"); x }, ] end end a, b = Y.new.f(0) 3.times do puts("a: #{a.call}") puts("b: #{b.call}") end Is z "on the stack" or "merely" in scope? As I understand it, z is bound to the closure. But how does Ruby know?