From: "David A. Black" Date: 2008-03-22T01:32:04+09:00 Subject: Re: dynamically defining a method on an instance that references vars in enclosing scope? Hi -- On Sat, 22 Mar 2008, Christopher J. Bottaro wrote: > Hello. I want to do this. > > instance = MyClass.new > x = 1 > def instance.foo > puts x > end > undefined local variable or method `x' for # > > How do get rid of that error? You can use define_method, which takes a block and therefore can use the local variables in scope at the time it's called. You'd have to do something equivalent to the familiar: class Object def singleton_class class << self self end end end (Aside to Matz: can we *please* have that in 1.9/2.0? :-) and then: instance.singleton_class.class_eval { define_method("foo") { puts x } } David -- Upcoming Rails training from David A. Black and Ruby Power and Light: ADVANCING WITH RAILS, April 14-17 2008, New York City CORE RAILS, June 24-27 2008, London (Skills Matter) See http://www.rubypal.com for details. Berlin dates coming soon!