From: dblack@... Date: 2006-08-07T04:01:51+09:00 Subject: Re: Singleton methods with method_missing Hi -- On Mon, 7 Aug 2006, Pat Maddox wrote: > I don't have any practical use for this, but I was experimenting a bit. > I just want to create singleton methods on objects of this class. > There's more to come, but this is the part I'm stuck at :) > > This code doesn't actually work, but I think it's close (I hope?) > > class OneShot > def method_missing(m) > class << self > define_method(m) { puts m.to_s } > end > send(m) > end > end > > When I do this I get "NameError: undefined local variable or method `m' > for #>" so I think it means that m just isn't > in scope for the singleton class. How can I define the singleton > method? Is there any way to use binding here? Try this: module Kernel def singleton_class # RCR 231 class << self; self; end end end class OneShot def method_missing(m) singleton_class.class_eval do define_method(m) { puts m } end end end o = OneShot.new o.x # method 'x' is created o.x # 'x' is printed David -- http://www.rubypowerandlight.com => Ruby/Rails training & consultancy ----> SEE SPECIAL DEAL FOR RUBY/RAILS USERS GROUPS! <----- http://dablog.rubypal.com => D[avid ]A[. ]B[lack's][ Web]log http://www.manning.com/black => book, Ruby for Rails http://www.rubycentral.org => Ruby Central, Inc.