gpt4 book ai didi

ruby - 为什么这个方法的参数是lambda,它是如何工作的

转载 作者:太空宇宙 更新时间:2023-11-03 17:26:47 25 4
gpt4 key购买 nike

摘自 Programming ruby​​ 1.9 书:

def my_while(cond, &body)
while cond.call
body.call
end
end

a=0

my_while -> { a < 3 } do
puts a
a += 1
end

产生:

0

1

2

最佳答案

该方法需要一个明确的参数cond,并且这个“条件”被假定为一个lambda/proc(这个假设是通过依赖cond.call来实现的) succeed) 并且必须显式传递给方法 my_while& 语法通过将变量隐式转换为 Proc 对象 ( see 'The ampersand' ) 来捕获变量中的方法 block (如果存在)。

block 在 Ruby 中不是真正的对象,因此必须使用 & 符号语法进行转换。将 block 绑定(bind)到 Proc 后,您可以像在任何其他 proc/lambda 上一样在其上发送 call 消息。

-> 语法是 lambda 的缩写,它将 block 转换为 Proc 对象(显式)。使用 lambda 和 Proc.new 之间也有细微差别。同样,维基百科:

Actually, there are two slight differences between lambda and Proc.new.

First, argument checking. The Ruby documentation for lambda states: Equivalent to Proc.new, except the resulting Proc objects check the number of parameters passed when called.

Second, there is a difference in the way returns are handled from the Proc. A return from Proc.new returns from the enclosing method (acting just like a return from a block, more on this later):

def try_ret_procnew
ret = Proc.new { return "Baaam" }
ret.call
"This is not reached"
end

# prints "Baaam"
puts try_ret_procnew

While return from lambda acts more conventionally, returning to its caller:

def try_ret_lambda
ret = lambda { return "Baaam" }
ret.call
"This is printed"
end

# prints "This is printed"
puts try_ret_lambda

With this in light, I would recommend using lambda instead of Proc.new, unless the behavior of the latter is strictly required. In addition to being way cooler a whopping two characters shorter, its behavior is less surprising.

关于ruby - 为什么这个方法的参数是lambda,它是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6945891/

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