define_method with singleton classes?

C

Csaba Henk

Hi!

I'd like to use an existing proc object as a method for a singleton class.

q = proc { ... }
def foo.bar(*a)
q[*a]
end

doesn't work, of course, as q is a local var (and I wouldn't like to
pollute the environment with globals...)

So what springs to my mind is sending a :define_method to the singleton
class... I just can't access that class:

class << foo
end
foo.send:)define_method,:bar,q)
=> NoMethodError: undefined method `define_method' for #<Object:0x401a2614>

That is, the singleton class is created, but the value of the variable foo
(be it anything at this point) doesn't behave as a class, but as the
original foo.

Any ideas, hints, pointers?

Thanks,
--
Csaba

"There's more to life, than books, you know but not much more..."
[The Smiths]
***
If you want to send me a mail, see it in the mailto link at
http://www.renyi.hu/~ekho/egyelore.html
 
N

nobu.nokada

Hi,

At Tue, 15 Jun 2004 18:48:34 +0900,
Csaba Henk wrote in [ruby-talk:103654]:
class << foo
end

This singleton class has no effect.
foo.send:)define_method,:bar,q)
=> NoMethodError: undefined method `define_method' for #<Object:0x401a2614>

That is, the singleton class is created, but the value of the variable foo
(be it anything at this point) doesn't behave as a class, but as the
original foo.

Yes, foo itself doesn't change. You need to call define_method
in the singleton class context.

q = proc {:q}
foo = Object.new
class << foo; self; end.module_eval do
define_method:)bar,q)
end
p foo.bar # => :q
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top