From: James Edward Gray II Date: 2006-12-12T07:14:31+09:00 Subject: Re: best way to dynamically create new instance methods 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)=> # >> bar = Dynamic.new(:bar) => # >> foo.foo("Hi") => "Hi" >> foo.bar("Hi") NoMethodError: undefined method `bar' for # from (irb):33 >> bar.bar("Hi") => "Hi" Hope that helps. James Edward Gray II