From: "Jesús Gabriel y Galán" Date: 2010-10-26T00:05:59+09:00 Subject: Re: Class eval does not work with self On Mon, Oct 25, 2010 at 4:03 PM, Andy Frank wrote: > I am experimenting with a test class to figure out why self.class_eval > does not seem to work.  Please see code below: > >  class Xclass >         def add_method(meth, work) >          self.class_eval %Q{ >                 def #{meth} >                         #{work} >                 end >                 } >         end > end > > This throws an error when I call the class like so: > > x = Xclass.new > x.add_method("add", "puts \"Hello World\"") > > > Error: > rb:3:in `add_method': undefined method `class_eval' for # > (NoMethodError) >  from test_dyn.rb:15:in `' > > > The fix has been to change self.class_eval  to Xclass.class_eval. > Anyone know why this is the case. Shouldn't self work. You can also use self.class.class_eval: irb(main):001:0> class Xclass irb(main):002:1> def add_method(meth,work) irb(main):003:2> self.class.class_eval %Q{ irb(main):004:2" def #{meth} irb(main):005:2" #{work} irb(main):006:2" end irb(main):007:2" } irb(main):008:2> end irb(main):009:1> end => nil irb(main):010:0> x = Xclass.new => # irb(main):011:0> x.add_method("add", 'puts "hello world"') => nil irb(main):012:0> x.add hello world Jesus.