Provide value for self when using Proc#call

后端 未结 3 579
既然无缘
既然无缘 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条回答
  • 2021-02-04 01:41

    You may want to use instance_exec because it allows you to pass arguments to the block whereas instance_eval does not.

    def eval_my_proc_with_args(*args, &block)
      instance_exec(*args, &block)
    end
    
    0 讨论(0)
  • 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 }
    => #<Proc:0x95cece4@(irb):1 (lambda)>
    >> class Dummy
    >>   def test
    >>     $p.call
    >>   end
    >> 
    >>   def test1
    >>     instance_eval(&$p)
    >>   end
    >> end
    
    >> d = Dummy.new
    => #<Dummy:0x946f7c8>
    >> d.test
    => main
    >> d.test1
    => #<Dummy:0x946f7c8>
    
    0 讨论(0)
  • 2021-02-04 01:53

    lambda defines a closure which means it will encapsulate the environment it had when it was defined. If you want self to be the caller just define a regular method or better yet use a block.

    0 讨论(0)
提交回复
热议问题