Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
    puts msg
  end
end

o = Object.new
define_say o, "hello world!"
o.say

This doesn't work because defining a singleton method via "def" is not a closure, so I get an exception that "msg" is an undefined variable or method.

What I would like to do is something like using the "define_method" method in the Module class, but as far as I can tell, this can only be used to define a method on a class... but I want a Singleton Method...

So, I would love to write it something like this:

def define_say(obj, msg)
  obj.define_singleton_method(:say) {
    puts msg
  }
end

Does anyone know how I can achieve this without having to create a method to store a Proc and then use the Proc within a singleton method? (basically, I want a clean, non-hacky way of doing this)

like image 536
Mike Stone Avatar asked Sep 25 '08 20:09

Mike Stone


1 Answers

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
like image 180
asymmetric Avatar answered Oct 06 '22 19:10

asymmetric