Define a method that is a closure in Ruby

后端 未结 3 1749
-上瘾入骨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:40

    This seems to work.

    class Foo
      def mess_it_up(o)
        x = "blah blah"
    
        o.instance_variable_set :@to_s_proc, Proc.new { puts x }
        def o.to_s
          @to_s_proc.call
        end
      end
    end
    
    var = Object.new
    Foo.new.mess_it_up(var)
    
    var.to_s
    

    The problem is that code in def is not evaluated until it's run, and in a new scope. So you have to save the block to an instance variable on the object first and retieve it later.

    And define_method doesn't work because it's a class method, meaning you would have to call it on the class of your object, giving that code to ALL instances of that class, and not just this instance.

提交回复
热议问题