The problem is of scope. foo is a method belonging to the 'instance' variable. 'x' is defined in global scope, but since its not $x its not a global variable. When you start using x inside the method, the interpreter doesn't recognize a 'x' variable defined, hence the error. Either, define x inside MyClass, or mark x as a global variable using $x, which would make... .... $x = 1 def instance.foo puts $x end to: Christopher I'd start off with a good introduction to scopes, that'll clear this scenario out. Plus buy the pickaxe book. Great read for beginners. On Sat, Mar 22, 2008 at 12:32 AM, David A. Black <dblack / rubypal.com> wrote: > 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 #<MyClass:0x31ca8c4> > > > > 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! > >