From: Sean O'Dell Date: 2004-07-03T05:20:01+09:00 Subject: Re: define_method to add a Class method? On Friday 02 July 2004 13:02, walter@mwsewall.com wrote: > > On Friday 02 July 2004 12:42, walter@mwsewall.com wrote: > > > How do you use define_method (or an equivalent) to add a method to a > > > Class. > > > > > > I want to create a class from a Database result set at runtime. I > > > was doing this by building a string and the evaling it, which works, > > > but wasn't all that rubyish and was ugly. > > > > > > I am now using an Anonymous class ie Class.new{...} and everything > > > is great except I can't seem to create a class method this way. > > > > > > I know I am missing something quite obvious, I just can't seem to > > > find it. > > > > > > Any pointers would be greatly appreciated. > > > > I'd stick with eval; it does the job. Something like this should work > > just fine: > > > > class_name = "MyClass" > > code = "print 'Hello, world!\n'" > > method_name = "my_method" > > > > eval_string = <<-EVAL > > class #{class_name} > > def #{method_name} > > #{code} > > end > > end > > EVAL > > > > eval eval_string > > > > o = MyClass.new > > o.my_method #=> "Hello, world!\n" > > > > > > Sean O'Dell > > That was how original version worked, and I can seem to port > everything except the creation of the class methods using the > Class.new{...} syntax. It just seems as if I am missing something. > Can we not add a class method using define_method. I have tried it > in combination with instance_eval, module_eval, directly on the > class, within the class, etc but so far no luck. > > I guess I just want to know if it can be done using a define_ method > or do we _have_ to use eval to add a class method this way. Well, I can add a method to that same class I created with an eval, this way: class MyClass define_method(:my_method2) do print("Hello, world, again!\n") end end o.my_method2 #=> "Hello, world, again!\n" Sean O'Dell