gpt4 book ai didi

ruby - 为什么带有 splat 参数的 Ruby 过程/ block 的行为与方法和 lambda 不同?

转载 作者:数据小太阳 更新时间:2023-10-29 07:00:36 26 4
gpt4 key购买 nike

为什么带有 splat 参数的 Ruby (2.0) 过程/ block 的行为与方法和 lambda 不同?

def foo (ids, *args)
p ids
end
foo([1,2,3]) # => [1, 2, 3]

bar = lambda do |ids, *args|
p ids
end
bar.call([1,2,3]) # => [1, 2, 3]

baz = proc do |ids, *args|
p ids
end
baz.call([1,2,3]) # => 1

def qux (ids, *args)
yield ids, *args
end
qux([1,2,3]) { |ids, *args| p ids } # => 1

这是对此行为的确认,但没有解释: http://makandracards.com/makandra/20641-careful-when-calling-a-ruby-block-with-an-array

最佳答案

Proc 对象有两种类型:lambda 以与普通方法相同的方式处理参数列表,proc 使用“技巧”(Proc#lambda?)。如果 proc 是唯一的参数,它将展开一个数组,忽略额外的参数,将 nil 分配给缺失的参数。您可以使用解构的 lambda 部分模仿 proc 行为:

->((x, y)) { [x, y] }[1]         #=> [1, nil]
->((x, y)) { [x, y] }[[1, 2]] #=> [1, 2]
->((x, y)) { [x, y] }[[1, 2, 3]] #=> [1, 2]
->((x, y)) { [x, y] }[1, 2] #=> ArgumentError

关于ruby - 为什么带有 splat 参数的 Ruby 过程/ block 的行为与方法和 lambda 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23945533/

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