Hi,

At Wed, 2 Oct 2002 12:27:07 +0900,
Mark Volkmann wrote:
> > But what if the name of the method I want to add (such as "test") isn't
> > determined until runtime?
> > Can I dynamically add a method like that?
> 
> I think I found the answer myself. Is there a better way than this?
> 
> obj = Object.new
> methodName = 'foo'
> methodDef = "def obj.#{methodName}; puts 'in my method'; end"
> eval(methodDef) # to add the method foo to the object obj
> obj.foo # to invoke it

It's an idiom to create methods dynamically, and if the method
body is determined:

  module Test
    def test
      puts "running the singleton test method"
    end
  end

  obj = Object.new
  methodName = 'foo'
  obj.extend(Test)
  (class << obj; self; end).module_eval {
    alias_method(methodName, :test)
  }
  obj.foo


You can use Module#define_method in 1.7.

-- 
Nobu Nakada