From: Richard Dale Date: 2004-08-18T00:30:57+09:00 Subject: Re: instance_eval lopex wrote: > Hi, > > I'm wondering why the following code works: > > class X > end > > x=X.new > a="some variable" > > > p x.instance_eval("a") > x.instance_eval{p a} > > why the x object knows the a variable ? Maybe this makes it clearer: class X end x=X.new a="some variable" def m1(thing, &block) block.call(thing) end def m2(thing) thing.instance_eval{p a} end p x.instance_eval("a") x.instance_eval{p a} m1(x) {p a} m2(x) The m1() method works because it is passed a block where 'a' is in scope. Then in m1 the block is called with that complete context, ie including 'a'. Whereas the m2() method fails because instance_eval() runs within the context of just 'thing', ie 'x', without its environment. "some variable" "some variable" "some variable" try_instance_eval.rb:12:in `m2': undefined local variable or method `a' for # (NameError) -- Richard