James Gray
12/11/2006 10:15:00 PM
On Dec 11, 2006, at 2:28 PM, Dan Tenenbaum wrote:
> 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):
>
> def baz(*args)
> args[0]
> end
>> class Dynamic
>> def initialize(name)
>> create_method(name)
>> end
>> private
>> def create_method(name)
>> class << self; self end.send(:define_method, name) { |*args|
args.first }
>> end
>> end
=> nil
>> foo = Dynamic.new(:foo)=> #<Dynamic:0x71dbd4>
>> bar = Dynamic.new(:bar)
=> #<Dynamic:0x71b3fc>
>> foo.foo("Hi")
=> "Hi"
>> foo.bar("Hi")
NoMethodError: undefined method `bar' for #<Dynamic:0x71dbd4>
from (irb):33
>> bar.bar("Hi")
=> "Hi"
Hope that helps.
James Edward Gray II