From: "Jesús Gabriel y Galán" Date: 2009-09-18T02:01:32+09:00 Subject: Re: Mucking about with dynamically adding methods to objects On Thu, Sep 17, 2009 at 5:28 PM, Paul Smith wrote: > 2009/9/17 Jesús Gabriel y Galán : >> On Thu, Sep 17, 2009 at 11:44 AM, Paul Smith wrote: > I think I have a lot more reading to do before > > irb(main):014:2> (class << obj;self;end).instance_eval do > irb(main):015:3* define_method :talk do > > makes any kind of sense. David's article is a good starting point to understand singleton classes and methods. Anyway, (class << obj; self; end) is a very common idiom to access the singleton class of an object. Some people even do: class Object def singleton_class class << self; self; end; end end Maybe with this addition, what I wrote is a little bit more clear: obj.singleton_class.instance_eval do define_method :talk do puts str end end As we need to refer to str, we use define_method, which doesn't define a new scope, so str is available in the block passed to define_method, which is a closure. In order to call define_method, which is private, we need an environment in which self is the object that we wan't to call define_method on*. In our case this object is the singleton class of "obj". The method instance_eval does exactly that: evaluate the block in a context in which self is set to the receiver of instance_eval. Hope this clarifies a little bit more. * Another way is to use send obj.singleton_class.send(:define_method, :talk) do puts str end but I like instance_eval better. Jesus.