From: Thomas Sondergaard Date: 2002-05-02T06:30:12+09:00 Subject: Re: is this FAQ material? -> adding instance methods to an object.... Might be. I think this is nicer for adding methods from inside a method definition: def get_object_with_name anObject = MyObject.new class << anObject def name @name end end anObject end Thomas On Wed, 2002-05-01 at 22:50, Patrick May wrote: > I was trying to add instance methods to an object. I figured this out > by looking at some library source, but I had problems finding this > info on ruby talk or in the FAQ. > > I know that I've seen this question answered on the list before, but > it's hard to narrow down to it. The search terms "define instance > methods object" touches on a wide variety of messages :-) > > I didn't see it when I looked at the FAQ at > http://www.rubycentral.com/faq/rubyfaq.html > > Is this something that is worth a FAQ entry? Something like: > > * How can I define methods on an object at run time? > > class MyObject > @name = "name" > end > > anObject = MyObject.new > def anObject.name > @name > end > > puts anObject.name # <= returns "name" > > # example from inside a method definition: > > def get_object_with_name > anObject = MyObject.new > eval <<-END > def anObject.name > @name > end > END > anObject > end > > foo = get_object_with_name > puts foo.name # <= returns "name" > > ~ Patrick