From: Dan T.
Sent: Monday, December 11, 2006 1:28 PM
To: ruby-talk ML
Subject: best way to dynamically create new instance methods
[snip]
What I want create_method() to do (simplified here) is, given the
argument “baz”, add a method to the current instance of Foo that would
look like this if it were a traditional method (that is, not
dynamically
created):
Assuming that you want each instance of foo to have its own list of
methods:
class Foo
def initialize( *method_names )
method_names.each{ |meth_name|
create_method( meth_name )
}
end
def create_method( meth_name )
( class << self; self; end ).class_eval{
define_method( meth_name ){ |*args|
args[0]
}
}
end
end
f1 = Foo.new( :bar, ‘baz’ )
p f1.bar( ‘a’, ‘b’, ‘c’ )
#=> “a”
f2 = Foo.new( ‘whee’ )
p f2.whee( ‘yahoo’ )
#=> “yahoo”
p f2.bar
#=> undefined method `bar’ for #Foo:0x2833f90 (NoMethodError)