So, I want to define a singleton method for an object, but I want to do it using a closure.
For example,
def define_say(obj, msg)
def obj.say
p
Here's an answer which does what you're looking for
def define_say(obj, msg)
# Get a handle to the singleton class of obj
metaclass = class << obj; self; end
# add the method using define_method instead of def x.say so we can use a closure
metaclass.send :define_method, :say do
puts msg
end
end
Usage (paste from IRB)
>> s = "my string"
=> "my string"
>> define_say(s, "I am S")
=> #<Proc:0xb6ed55b0@(irb):11>
>> s.say
I am S
=> nil
For more info (and a little library which makes it less messy) read this:
http://viewsourcecode.org/why/hacking/seeingMetaclassesClearly.html
As an aside, If you're a ruby programmer, and you HAVEN'T read that, go do it now~!
Object#define_singleton_method was added to ruby-1.9.2 by the way:
def define_say(obj, msg)
obj.define_singleton_method(:say) do
puts msg
end
end