Define a method that is a closure in Ruby

后端 未结 3 1751
-上瘾入骨i
-上瘾入骨i 2021-02-01 09:52

I\'m re-defining a method in an object in ruby and I need the new method to be a closure. For example:

def mess_it_up(o)
  x = \"blah blah\"

  def o.to_s
    pu         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-01 10:36

    Feature #1082 implemented in Ruby 1.9.2 makes this an easy task with Object#define_singleton_method:

    def mess_it_up(o)
      x = "blah blah"
    
      # Use Object#define_singleton_method to redefine `to_s'
      o.define_singleton_method(:to_s) { x }
    end
    

    The concepts involved are still the same as in my previous answer, which provides a more in-depth description of how this works in Ruby's object model, as well as a Object#define_method definition that is conceptually the same as Ruby 1.9.2's Object#define_singleton_method.

    Other methods that you might find useful for similar tasks:

    • Object#singleton_class
    • Object#singleton_methods
    • Object#respond_to_missing? (great blog post here)

提交回复
热议问题