Sander Land
8/6/2006 7:09:00 PM
On 8/6/06, Pat Maddox <devlists-ruby-talk@devlists.com> 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?)
>
> When I do this I get "NameError: undefined local variable or method `m'
> for #<Class:#<OneShot:0x32cf74>>" 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?
It is close :)
class<<self .... end is not a closure (only blocks are), so m is not
defined there. A solution is to use blocks for everything, using *eval
functions.
class OneShot
def method_missing(m,*a)
puts "method #{m} missing!"
(class<<self;self;end).class_eval {
define_method(m) { puts m.to_s }
}
send(m)
end
end
a = OneShot.new
a.foo
a.foo
b = OneShot.new
b.foo
b.foo
output:
method foo missing!
foo
foo
method foo missing!
foo
foo
Which is what you want, right?