问题描述
Ruby 在通过 Proc.new
和 lambda
(或 1.9 中的 ->()
运算符)创建的 Procs 之间存在差异.似乎非 lambda Procs 会在块参数之间传递一个数组;通过 lambda 创建的过程没有.
Ruby has differences between Procs created via Proc.new
and lambda
(or the ->()
operator in 1.9). It appears that non-lambda Procs will splat an array passed in across the block arguments; Procs created via lambda do not.
p = Proc.new { |a,b| a + b}
p[[1,2]] # => 3
l = lambda { |a,b| a + b }
l[[1,2]] # => ArgumentError: wrong number of arguments (1 for 2)
有人了解这种行为背后的动机吗?
Does anyone have any insight into the motivations behind this behavior?
推荐答案
lambda 和非 lambda Proc
s 有两个主要区别:
There are two main differences between lambdas and non-lambda Proc
s:
- 就像方法一样,lambda 从自身返回,而非 lambda
Proc
从封闭方法返回,就像块一样. - 就像方法一样,lambdas 有严格的参数检查,而非 lambda
Proc
s 有松散的参数检查,就像块一样.
- Just like methods, lambdas return from themselves, whereas non-lambda
Proc
s return from the enclosing method, just like blocks. - Just like methods, lambdas have strict argument checking, whereas non-lambda
Proc
s have loose argument checking, just like blocks.
或者,简而言之:lambda 的行为类似于方法,非 lambda Proc
的行为类似于块.
Or, in short: lambdas behave like methods, non-lambda Proc
s behave like blocks.
您所看到的是#2 的一个实例.除了非 lambda Proc
和 lambda 之外,用一个块和一个方法尝试它,你会看到.(如果没有这种行为,Hash#each
将是一个真正的 PITA 使用,因为它确实产生一个包含两个元素的数组,但是你几乎总是想把它当作两个参数.)
What you are seeing there is an instance of #2. Try it with a block and a method in addition to a non-lambda Proc
and a lambda, and you'll see. (Without this behavior, Hash#each
would be a real PITA to use, since it does yield an array with two-elements, but you pretty much always want to treat it as two arguments.)
这篇关于Proc 和 Lambda 之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!