From: "David A. Black" Date: 2009-09-10T21:49:52+09:00 Subject: Re: defining a singleton method dynamically Hi -- On Thu, 10 Sep 2009, 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? def starts a new local scope, so it won't see label. You need to get into obj's singleton class, using code blocks rather than class and def blocks: def foo(obj, label) (class << obj; self; end).class_eval do define_method("name") { label } end end You could also do something with eval but I prefer to use the code block approach rather than the string-eval'ing approach. (Still hoping for Object#singleton_class to make the access to the singleton class a little less awkward :-) 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.