From: Sean O'Dell Date: 2004-07-03T04:53:26+09:00 Subject: Re: define_method to add a Class method? 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