From: Jan Svitok Date: 2006-10-02T22:25:06+09:00 Subject: Re: Creating dynamically named singleton methods. Syntax question. On 10/2/06, Luke Stark wrote: > You may create singleton methods like so: > > foo = MyThing.new > > def foo.do_stuff > "code" > end > > But I cannot seem to grock the syntax that would allow me to name the > method from a variable. Such as: > > foo = MyThing.new > bar = "do_stuff" > def foo.%{#{bar}} #This is totally wrong I think. > "code" > end > > Any suggestions? I'm starting to get a spinning head. :) > > To be clear, I want to create a singleton method on the instance of > MyThing, not add the method to the MyThing class. > > This is mentioned here: > > http://www.rubyist.net/~slagell/ruby/singletonmethods.html > > but I'd like to do it dynamically. > > Many thanks! foo = Object.new def foo.bar "bar" end meth = "baz" eval <<-EOF def foo.#{meth} ; "#{meth}" ; end EOF meth = "bax" foo.instance_eval <<-EOF def #{meth} ; "#{meth}" ; end EOF puts foo.bar puts foo.baz puts foo.bax