Is it possible to define a Ruby singleton method using a block? Is it possible to define a Ruby singleton method using a block? ruby ruby

Is it possible to define a Ruby singleton method using a block?


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  endend


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  endend

Usage (paste from IRB)

>> s = "my string"=> "my string">> define_say(s, "I am S")=> #<Proc:0xb6ed55b0@(irb):11>>> s.sayI 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~!