Stefano Crocco
8/11/2008 3:04:00 PM
On Monday 11 August 2008, Patrick Li wrote:
> Hi,
> I'm still really confused about Ruby Closures.
>
> At first I thought closures are just blocks who "remember" the context
> that they were defined in (so that they can refer to local variables and
> methods)
>
> And then I discovered instance_eval (which changes the context that a
> block is evaluated in).
>
> When you use instance_eval you can't call local methods anymore
> (because, the scope has changed, and those methods aren't local
> anymore).
>
> But how come I can still use local variables?
>
> myStr = "myString"
> o = Object.new
> o.instance_eval do
> @str = myStr # <- why does this still work?
> def method
> puts @str
> end
> end
>
> So are local variables sort of an exception to instance_eval? And in the
> above example, how come it won't work anymore if I change myStr into an
> instance variable @myStr?
instance_eval doesn't change scope. Its only effect is to change the value of
the special local variable self. This explains why you can't access instance
variables anymore: with self changed, the instance variables are instance
variables of the new self (that is, the receiver of instance_eval). The same
is true for instance methods. Local variables, on the other hand, are
unaffected by the change of self and so you can still use them.
I hope this helps
Stefano