From: mutahhir hayat Date: 2008-03-22T02:27:40+09:00 Subject: Re: dynamically defining a method on an instance that references vars in enclosing scope? > I know that the problem is scope. That's why I suggested a way to > manipulate the scope :-) > > I definitely would not (and deliberately did not) throw a global > variable at it. Also, defining x inside MyClass doesn't help, because > that's also a different local scope. I wasn't sure, but running an intermix of your code with the original still would give the same error in irb. I wasn't advocating the use of globals, ( though, come to think about it, i do feel bad now even mentioning it :P) but I didn't consider that x wouldn't be usable. :) I'm still getting used to this metaprogramming thing, but how did you change scope? In my view, the scope remains exactly same, you just allowed the method to be inserted into the object instance dynamically. Anyways, simplest i found was: (swearing never to mention global again... :P) class MyClass attr_accessor :x #... or if you want you could do # def initialize(x); @x = x; end end instance = MyClass.new def instance.foo puts x end instance.x = 1 instance.foo would work. MT. > > > David