gpt4 book ai didi

Ruby lambda 的 proc 和 'instance_eval'

转载 作者:数据小太阳 更新时间:2023-10-29 08:42:43 28 4
gpt4 key购买 nike

当我将 lambda 作为 block 传递给 instance_eval 时,它似乎传递了一个额外的参数:

lamb = -> { puts 'hi' }
proc = Proc.new { puts 'hi' }
instance_eval(&lamb)
# >> ArgumentError: wrong number of arguments (given 1, expected 0)
# from (irb):5:in `block in irb_binding'
# from (irb):7:in `instance_eval'
instance_eval(&proc)
# => hi
instance_exec(&lamb)
# => hi

为什么会这样?请注意,此问题与 lambda 为何抛出错误无关。这是很好理解的。问题是关于为什么 instance_eval 将接收方的 self 作为参数发送。它不是必需的,而且令人困惑。并且 AFAIK 没有记录。

This有帮助,但没有解释为什么 ruby 会这样做。 instance_eval 的重点是将 self 设置为接收者;为什么还通过将 self 传递给 proc 来混淆事情?

最佳答案

来自文档

For procs created using lambda or ->() an error is generated if the wrong number of parameters are passed to a Proc with multiple parameters. For procs created using Proc.new or Kernel.proc, extra parameters are silently discarded.

在你的例子中,lambproc 都使用一个参数调用

From the docs of instance_eval

When instance_eval is given a block, obj is also passed in as the block's only argument

instance_evalBasicObject 类的方法,可以在实例中调用。例如,给定的 block 将可以访问私有(private)方法。

class Test
def call
secret_number + 100
end
private
def secret_number
42
end
end

test = Test.new
show_secret = -> (obj) { puts secret_number }

test.instance_eval(&show_secret) # print 42

没有当前上下文的实例 self 将作为参数传递。我认为 instance_eval 更适合在对象中调用它。

From the docs of instance_eval

In order to set the context, the variable self is set to obj while the code is executing, giving the code access to obj's instance variables and private methods.

关于Ruby lambda 的 proc 和 'instance_eval',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52618934/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com