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

后端 未结 2 898
隐瞒了意图╮
隐瞒了意图╮ 2020-12-31 10:17

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         


        
2条回答
  •  粉色の甜心
    2020-12-31 10:35

    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
    

提交回复
热议问题