From: Nilesh Trivedi Date: 2009-09-10T21:52:05+09:00 Subject: Re: defining a singleton method dynamically --00151747921cbfa09c047338881e Content-Type: text/plain; charset=ISO-8859-1 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? cheers nilesh --00151747921cbfa09c047338881e--