From: Robert Klemme Date: 2012-02-24T01:35:59+09:00 Subject: Re: How are closures implemented? On Thu, Feb 23, 2012 at 4:53 PM, Ralph Shnelvar wrote: > 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? I think both. > As I understand it, z is bound to the closure. Correct. > But how does Ruby know? z is a local variable in the scope which invokes define_method and thus visible to the method body because you did not use def which introduces a completely separate scope and not a nested scope as a block does. From the scoping perspective your example is no different than z = 0 10.times.to_a.each do |y| z += y end The only difference really is that by using define_method you retain _another_ closure as method body from which the (additionally to storing the lambdas in a variable after the method call). So you have 1. closure is the method body and it has access to z because that is in the scope visible to the block passed to #define_method. 2. and 3. closure are the two lambdas returned which access the same z also visible to the first closure. Typically programming language implementations store local variables on the stack so it does not make a difference whether we are talking about a method argument or local variable - both would sit on the stack. For the details you would have to look at the source. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/