From: "David A. Black" Date: 2009-09-10T21:56:44+09:00 Subject: Re: defining a singleton method dynamically Hi -- On Thu, 10 Sep 2009, Nilesh Trivedi wrote: > On Thu, Sep 10, 2009 at 6:05 PM, Nilesh Trivedi wrote: > >> How do I define a singleton method dynamically? >> >> I have code similar to this: >> >> def foo(obj,label) >> def obj.name; label; end #we want to define a singleton method called >> "name" on obj which returns the value in label >> puts obj.name #this is an example. Actually I have some code here which >> expects this singleton method in obj >> end >> >> When I try to run this as foo(Object.new,"xyz"), it throws a "NameError: >> undefined local variable or method `label' for #" whereas >> I want it to print "xyz" to screen. >> >> Of course, line 2 in method foo is not correct. But what is the correct >> way? >> > > Replacing line 2 by: > > obj.instance_eval "def name; '#{label}'; end" > > does get the behaviour that I want. Is this the best way to do this or is > there a better, cleaner way? It may be overkill, but I pretty much always choose the block form of *_eval rather than the string form, as per my response of a couple of minutes ago. If you're going to eval strings, you could also do: eval "def obj.name; '#{label}'; end" David -- David A. Black / Ruby Power and Light, LLC / http://www.rubypal.com Ruby/Rails training, mentoring, consulting, code-review Latest book: The Well-Grounded Rubyist (http://www.manning.com/black2) September Ruby training in NJ has been POSTPONED. Details to follow.