Provide value for self when using Proc#call

后端 未结 3 610
既然无缘
既然无缘 2021-02-04 01:05

When using Proc#call to call a lambda function in Ruby, self always ends up with the value that it had when the function was defined, rather than the value it has w

3条回答
  •  Happy的楠姐
    2021-02-04 01:47

    You're looking for instance_eval, which evaluates a lambda in the context of the calling object.

    >> $p = proc { self }
    => #
    >> class Dummy
    >>   def test
    >>     $p.call
    >>   end
    >> 
    >>   def test1
    >>     instance_eval(&$p)
    >>   end
    >> end
    
    >> d = Dummy.new
    => #
    >> d.test
    => main
    >> d.test1
    => #
    

提交回复
热议问题