Change the binding of a Proc in Ruby

后端 未结 4 1497
春和景丽
春和景丽 2020-12-15 05:48

I have this code:

 l = lambda { a }
 def some_function
     a = 1
 end

I just want to access a by the lambda and a special sco

4条回答
  •  伪装坚强ぢ
    2020-12-15 06:46

    class Proc
        def call_with_obj(obj, *args)
            m = nil
            p = self
            Object.class_eval do
                define_method :a_temp_method_name, &p
                m = instance_method :a_temp_method_name; remove_method :a_temp_method_name
            end
            m.bind(obj).call(*args)
        end
    end
    

    And then use it as:

    class Foo
        def bar
            "bar"
        end
    end
    
    p = Proc.new { bar }
    
    bar = "baz"
    
    p.call_with_obj(self) # => baz
    p.call_with_obj(Foo.new) # => bar
    

提交回复
热议问题