何时使用 lambda,何时使用 Proc.new?
在 Ruby 1.8 中,一方面 proc/lambda 与 Proc.new
之间存在细微差别。
- 这些差异是什么?
- 您能否给出如何决定选择哪一个的指南?
- 在 Ruby 1.9 中,proc 和 lambda 是不同的。 这是怎么回事?
In Ruby 1.8, there are subtle differences between proc/lambda on the one hand, and Proc.new
on the other.
- What are those differences?
- Can you give guidelines on how to decide which one to choose?
- In Ruby 1.9, proc and lambda are different. What's the deal?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(14)
值得强调的是,过程中的
return
从词法封闭的方法返回,即创建过程的方法,而不是调用的方法程序。 这是 procs 的闭包属性的结果。 因此,以下代码不会输出任何内容:虽然 proc 在
foobar
中执行,但它是在foo
中创建的,因此return
退出foo< /code>,而不仅仅是
foobar
。 正如 Charles Caldwell 上面所写,它有一种 GOTO 的感觉。 在我看来,return 在其词法上下文中执行的块中很好,但在不同上下文中执行的过程中使用时就不太直观了。It's worth emphasizing that
return
in a proc returns from the lexically enclosing method, i.e. the method where the proc was created, not the method that called the proc. This is a consequence of the closure property of procs. So the following code outputs nothing:Although the proc executes in
foobar
, it was created infoo
and so thereturn
exitsfoo
, not justfoobar
. As Charles Caldwell wrote above, it has a GOTO feel to it. In my opinion,return
is fine in a block that is executed in its lexical context, but is much less intuitive when used in a proc that is executed in a different context.提供进一步说明:
Joey 说
Proc.new
的返回行为令人惊讶。 然而,当您考虑到 Proc.new 的行为类似于块时,这并不奇怪,因为这正是块的行为方式。 另一方面,lambas 的行为更像方法。这实际上解释了为什么 Proc 在 arity(参数数量)方面很灵活,而 lambda 则不然。 块不需要提供所有参数,但方法需要提供(除非提供默认值)。 虽然提供 lambda 参数默认值在 Ruby 1.8 中不是一个选项,但现在 Ruby 1.9 中通过替代 lambda 语法(如 webmat 所指出的)支持它:
并且 Michiel de Mare(OP)关于 Procs 和 lambda 行为相同的说法是不正确的Ruby 1.9 中具有 arity。 我已验证它们仍然保持上述 1.8 中指定的行为。
break
语句实际上在 Procs 或 lambda 中没有多大意义。 在 Procs 中,中断将使您从已经完成的 Proc.new 返回。 打破 lambda 没有任何意义,因为它本质上是一个方法,而且你永远不会打破方法的顶层。next
、redo
和raise
在 Procs 和 lambda 中的行为相同。 而retry
两者都是不允许的,并且会引发异常。最后,永远不应该使用 proc 方法,因为它不一致并且具有意外的行为。 在 Ruby 1.8 中它实际上返回一个 lambda! 在 Ruby 1.9 中,这个问题已被修复并返回一个 Proc。 如果您想创建一个 Proc,请坚持使用
Proc.new
。要了解更多信息,我强烈推荐 O'Reilly 的《The Ruby Programming Language》,它是我大部分信息的来源。
To provide further clarification:
Joey says that the return behavior of
Proc.new
is surprising. However when you consider that Proc.new behaves like a block this is not surprising as that is exactly how blocks behave. lambas on the other hand behave more like methods.This actually explains why Procs are flexible when it comes to arity (number of arguments) whereas lambdas are not. Blocks don't require all their arguments to be provided but methods do (unless a default is provided). While providing lambda argument default is not an option in Ruby 1.8, it is now supported in Ruby 1.9 with the alternative lambda syntax (as noted by webmat):
And Michiel de Mare (the OP) is incorrect about the Procs and lambda behaving the same with arity in Ruby 1.9. I have verified that they still maintain the behavior from 1.8 as specified above.
break
statements don't actually make much sense in either Procs or lambdas. In Procs, the break would return you from Proc.new which has already been completed. And it doesn't make any sense to break from a lambda since it's essentially a method, and you would never break from the top level of a method.next
,redo
, andraise
behave the same in both Procs and lambdas. Whereasretry
is not allowed in either and will raise an exception.And finally, the
proc
method should never be used as it is inconsistent and has unexpected behavior. In Ruby 1.8 it actually returns a lambda! In Ruby 1.9 this has been fixed and it returns a Proc. If you want to create a Proc, stick withProc.new
.For more information, I highly recommend O'Reilly's The Ruby Programming Language which is my source for most of this information.
return
语句:lambda
创建的过程和使用Proc.new
创建的过程之间的另一个重要但微妙的区别是它们如何处理 >lambda 创建的过程,return
语句仅从过程本身返回Proc.new
创建的过程中,return
> 语句有点令人惊讶:它不仅从 proc 返回控制,还从包含该 proc 的方法返回控制!这是
lambda
创建的 proc 的return< /code> 正在行动。 它的行为方式可能符合您的预期:
现在这是一个
Proc.new
创建的 proc 的return
执行相同的操作。 您将看到 Ruby 打破了大肆吹嘘的最小意外原则的情况之一:由于这种令人惊讶的行为(以及更少的打字),我倾向于使用
lambda
而不是 < code>Proc.new 制作过程时。Another important but subtle difference between procs created with
lambda
and procs created withProc.new
is how they handle thereturn
statement:lambda
-created proc, thereturn
statement returns only from the proc itselfProc.new
-created proc, thereturn
statement is a little more surprising: it returns control not just from the proc, but also from the method enclosing the proc!Here's
lambda
-created proc'sreturn
in action. It behaves in a way that you probably expect:Now here's a
Proc.new
-created proc'sreturn
doing the same thing. You're about to see one of those cases where Ruby breaks the much-vaunted Principle of Least Surprise:Thanks to this surprising behavior (as well as less typing), I tend to favor using
lambda
overProc.new
when making procs.Proc 较旧,但 return 的语义对我来说非常违反直觉(至少在我学习该语言时),因为:
Lambda 在功能上更安全,更容易推理——我总是使用它而不是 proc。
Proc is older, but the semantics of return are highly counterintuitive to me (at least when I was learning the language) because:
Lambda is functionally safer and easier to reason about - I always use it instead of proc.
我发现此页面显示了
Proc.new
和之间的区别>lambda
是。 根据该页面,唯一的区别是 lambda 对它接受的参数数量很严格,而 Proc.new 将缺少的参数转换为 nil。 以下是说明差异的 IRB 会话示例:该页面还建议使用 lambda,除非您特别想要容错行为。 我同意这种观点。 使用 lambda 似乎更简洁一些,并且由于差异如此微不足道,因此在一般情况下它似乎是更好的选择。
至于 Ruby 1.9,抱歉,我还没有研究过 1.9,但我不认为他们会改变那么多(不过不要相信我的话,看来你已经听说过一些变化,所以我可能错了)。
I found this page which shows what the difference between
Proc.new
andlambda
are. According to the page, the only difference is that a lambda is strict about the number of arguments it accepts, whereasProc.new
converts missing arguments tonil
. Here is an example IRB session illustrating the difference:The page also recommends using lambda unless you specifically want the error tolerant behavior. I agree with this sentiment. Using a lambda seems a tad more concise, and with such an insignificant difference, it seems the better choice in the average situation.
As for Ruby 1.9, sorry, I haven't looked into 1.9 yet, but I don't imagine they would change it all that much (don't take my word for it though, it seems you have heard of some changes, so I am probably wrong there).
对于细微的差别我不能说太多。 不过,我可以指出,Ruby 1.9 现在允许 lambda 和块使用可选参数。
以下是 1.9 下的 stable lambda 的新语法:
Ruby 1.8 没有该语法。 声明块/lambda 的传统方式也不支持可选参数:
然而,Ruby 1.9 即使使用旧语法也支持可选参数:
如果您想为 Leopard 或 Linux 构建 Ruby1.9,请查看 这篇文章(无耻的自我推销)。
I can't say much about the subtle differences. However, I can point out that Ruby 1.9 now allows optional parameters for lambdas and blocks.
Here's the new syntax for the stabby lambdas under 1.9:
Ruby 1.8 didn't have that syntax. Neither did the conventional way of declaring blocks/lambdas support optional args:
Ruby 1.9, however, supports optional arguments even with the old syntax:
If you wanna build Ruby1.9 for Leopard or Linux, check out this article (shameless self promotion).
Ruby 中的闭包 很好地概述了块、lambda 和 proc 的工作方式使用 Ruby 工作,使用 Ruby。
Closures in Ruby is a good overview for how blocks, lambda and proc work in Ruby, with Ruby.
观察它的一个好方法是 lambda 是在自己的作用域中执行的(就好像它是一个方法调用),而 Procs 可以被视为与调用方法内联执行,至少这是决定使用哪一个的好方法在每种情况下。
A good way to see it is that lambdas are executed in their own scope (as if it was a method call), while Procs may be viewed as executed inline with the calling method, at least that's a good way of deciding wich one to use in each case.
简短的回答:重要的是
return
的作用:lambda 从自身返回,而 proc 从自身以及调用它的函数返回。不太清楚的是为什么要使用它们。 lambda 是我们期望的事情在函数式编程意义上应该做的事情。 它基本上是一个自动绑定当前范围的匿名方法。 在这两者中,lambda 是您可能应该使用的一个。
另一方面,Proc 对于实现语言本身确实非常有用。 例如,您可以使用它们实现“if”语句或“for”循环。 在过程中找到的任何返回都将从调用它的方法中返回,而不仅仅是“if”语句。 这就是语言的工作原理,“if”语句的工作原理,所以我猜测 Ruby 在幕后使用了它,他们只是暴露了它,因为它看起来很强大。
仅当您正在创建新的语言结构(例如循环、if-else 结构等)时,您才真正需要它。
Short answer: What matters is what
return
does: lambda returns out of itself, and proc returns out of itself AND the function that called it.What is less clear is why you want to use each. lambda is what we expect things should do in a functional programming sense. It is basically an anonymous method with the current scope automatically bound. Of the two, lambda is the one you should probably be using.
Proc, on the other hand, is really useful for implementing the language itself. For example you can implement "if" statements or "for" loops with them. Any return found in the proc will return out of the method that called it, not the just the "if" statement. This is how languages work, how "if" statements work, so my guess is Ruby uses this under the covers and they just exposed it because it seemed powerful.
You would only really need this if you are creating new language constructs like loops, if-else constructs, etc.
我没有注意到问题中第三种方法“proc”的任何评论,该方法已被弃用,但在 1.8 和 1.9 中处理方式不同。
这是一个相当详细的示例,可以轻松看出三个相似调用之间的差异:
I didn't notice any comments on the third method in the queston, "proc" which is deprecated, but handled differently in 1.8 and 1.9.
Here's a fairly verbose example that makes it easy to see the differences between the three similar calls:
lambda 按预期工作,就像在其他语言中一样。
有线
Proc.new
令人惊讶且令人困惑。由
Proc.new
创建的 proc 中的return
语句不仅会从自身返回控制权,还会从包含它的方法返回控制权。您可以认为
Proc.new
将代码插入到封闭的方法中,就像 block 一样。但是 Proc.new 创建一个对象,而 block 是对象的一部分。
lambda 和 Proc.new 之间还有另一个区别,那就是它们对(错误)参数的处理。
lambda 会对此进行抱怨,而 Proc.new 会忽略额外的参数或将缺少参数视为 nil。
顺便说一句,Ruby 1.8 中的 proc 创建了一个 lambda,而 Ruby 1.9+ 的行为类似于 Proc.new,这确实令人困惑。
lambda works as expected, like in other languages.
The wired
Proc.new
is surprising and confusing.The
return
statement in proc created byProc.new
will not only return control just from itself, but also from the method enclosing it.You can argue that
Proc.new
inserts code into the enclosing method, just like block.But
Proc.new
creates an object, while block are part of an object.And there is another difference between lambda and
Proc.new
, which is their handling of (wrong) arguments.lambda complains about it, while
Proc.new
ignores extra arguments or considers the absence of arguments as nil.BTW,
proc
in Ruby 1.8 creates a lambda, while in Ruby 1.9+ behaves likeProc.new
, which is really confusing.我在这方面有点晚了,但是有一件关于 Proc.new 的伟大但鲜为人知的事情根本没有在评论中提及。 正如文档:
也就是说,Proc.new 可以链接生成方法:
I am a bit late on this, but there is one great but little known thing about
Proc.new
not mentioned in comments at all. As by documentation:That said,
Proc.new
lets to chain yielding methods:详细说明 Accordion Guy 的响应:
请注意,
Proc.new
通过传递一个块来创建一个 proc out。 我相信 lambda {...} 被解析为一种文字,而不是传递块的方法调用。 从附加到方法调用的块内部返回将从方法而不是块返回,Proc.new 情况就是一个例子。(这是 1.8。我不知道如何转换为 1.9。)
To elaborate on Accordion Guy's response:
Notice that
Proc.new
creates a proc out by being passed a block. I believe thatlambda {...}
is parsed as a sort of literal, rather than a method call which passes a block.return
ing from inside a block attached to a method call will return from the method, not the block, and theProc.new
case is an example of this at play.(This is 1.8. I don't know how this translates to 1.9.)
恕我直言,return 的行为差异是两者之间最重要的差异。我也更喜欢 lambda,因为它比 Proc.new 打字更少:-)
The difference in behaviour with
return
is IMHO the most important difference between the 2. I also prefer lambda because it's less typing than Proc.new :-)