使用 Proc#call 时为自己提供价值 [英] Provide value for self when using Proc#call

查看:36
本文介绍了使用 Proc#call 时为自己提供价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ruby 中使用 Proc#call 调用 lambda 函数时,self 总是以定义函数时的值结束,而不是调用函数时的值,例如:

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 when the function is called, for example:

$p = lambda { self }

class Dummy
  def test
    $p.call
  end
end

d = Dummy.new

> d.test
=> main

调用 test 返回 main,当我想要它返回的是 #<Dummy:0xf794> - Dummy,这是在代码中我调用 $p 处的 self 值.

Calling test returns main, when what I intended it to return is #<Dummy:0xf794> - an instance of Dummy, which was the value of self at the point in the code where I called $p.

在Javascript中,我只是将我想成为被调用者"的对象作为第一个参数传递给call.Ruby 中有没有这样的功能,允许我设置一个任意对象,或者至少是 self 的当前值,作为 self 的新值,当我调用 Proc?

In Javascript, I would just pass the object that I want to be the "callee" as the first argument to call. Is there any such functionality in Ruby, allowing me to set an arbitrary object, or at least the current value of self, as the new value for self when I call a Proc?

推荐答案

您正在寻找 instance_eval,它在调用对象的上下文中计算 lambda.

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>

这篇关于使用 Proc#call 时为自己提供价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆