2009/9/17 Jesù¸ Gabriel y GaláÏ <jgabrielygalan / gmail.com>: > On Thu, Sep 17, 2009 at 11:44 AM, Paul Smith <paul / pollyandpaul.co.uk> wrote: > >> But my next logical leap doesn't work: >> >> Changing the talkify method to this: >> >> def talkify(obj, str) >> ef obj.talk >> uts str >> nd >> 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. hat 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 > => #<Object:0xb7d62cf4> > irb(main):023:0> A.new.talkify o,"hi" > => #<Proc:0xb7d64f40@(irb):15> > 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