On Thu, Feb 23, 2012 at 4:53 PM, Ralph Shnelvar <ralphs / dos32.com> wrote:
> Ok ... modifying your example
>
>
> class Y
>  ¨Â ±°
>
>  ¨Âåæéîåßíåôèïä ºæ äï üø>  ¨Â
>  ¨Âáíâ䫽 ðõô󨢫½ úº ú½£ûúýø½£ûøý¢©ý¬
>  ¨Âáíâ䫽 °®µ»  ðõô󨢫½ °®µº ú½£ûúýø½£ûøý¢©ý¬
>  ¨Â
>  ¨Âîä
> end
>
> a, b = Y.new.f(0)
>
> 3.times do
>  ¨Âõôó¨¢á£ûá®ãáììý¢>  ¨Âõôó¨¢â£ûâ®ãáììý¢> 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/