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

后端 未结 2 822
隐瞒了意图╮
隐瞒了意图╮ 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:21

    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~!

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题