gpt4 book ai didi

Ruby:隐式 block 转换为 Proc

转载 作者:行者123 更新时间:2023-12-03 20:23:10 25 4
gpt4 key购买 nike

我的理解是必须产生隐式附加到方法的 block ;它不能被调用。所以我试图理解为什么会这样:

def execute_code
proc.call
end

execute_code { "Why does this work?" } # => "Why does this work?"
将 block 附加到此代码会成功执行。
有什么见解吗?我没有找到任何文档暗示隐式 block 会自动转换为 proc 对象并分配给变量 proc .
ruby 2.5.3

最佳答案

对于 Ruby 2.5.3,docs for Kernel#proc() 说:

Equivalent to Proc.new.


docs for Proc.new 说:

Creates a new Proc object, bound to the current context. Proc::new may be called without a block only within a method with an attached block, in which case that block is converted to the Proc object.


这就是您的示例中发生的情况。您调用 proc在带有 block 的方法中,并且 block 正在转换为 Proc.但是,此行为在以后的版本中发生了变化。如果您在 Ruby 2.7,1 中尝试,您将收到这样的警告(尽管它仍然有效):
proc.rb:2: warning: Capturing the given block using Kernel#proc is deprecated; use `&block` instead
在 Ruby 3 中,它根本不起作用(实际上表现得如您所料):
proc.rb:2:in `proc': tried to create Proc object without a block (ArgumentError)
from proc.rb:2:in `execute_code'
from proc.rb:5:in `<main>'
docs for 3.0.0虽然没有改变。这看起来像文档中的错误(它一直是 fixed in master )。看起来这是在 2014 的问题跟踪器中首次提出的。然后是 2019 .

关于Ruby:隐式 block 转换为 Proc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66879587/

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