From: Paul Smith Date: 2009-09-18T00:28:25+09:00 Subject: Re: Mucking about with dynamically adding methods to objects 2009/9/17 Jesús Gabriel y Galán : > On Thu, Sep 17, 2009 at 11:44 AM, Paul Smith wrote: > >> But my next logical leap doesn't work: >> >> Changing the talkify method to this: >> >> def talkify(obj, str) >>  def obj.talk >>    puts str >>  end >> end >> >> doesn't do what I mean - what it does is create a method called talk >> which tries to output obj.str which doesn't exist.  What I want is for >> the obj.talk method to return the literal string given to the >> fairy.talkify call. > > The problem here is that def starts a new scope, so str is undefined there. > This is a try with define_object instead: > > irb(main):012:0> class A > irb(main):013:1> def talkify(obj,str) > irb(main):014:2> (class << obj;self;end).instance_eval do > irb(main):015:3* define_method :talk do > irb(main):016:4* puts str > irb(main):017:4> end > irb(main):018:3> end > irb(main):019:2> end > irb(main):020:1> end > => nil > irb(main):021:0> o = Object.new > => # > irb(main):023:0> A.new.talkify o,"hi" > => # > irb(main):024:0> o.talk > hi > => nil > > We call define_method in the singleton class of obj. We need the > instance_eval because define_method is private. > > Hope this helps, > Thanks 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. -- Paul Smith http://www.nomadicfun.co.uk paul@pollyandpaul.co.uk