何时使用lambda,何时使用Proc.new? [英] When to use lambda, when to use Proc.new?
问题描述
在Ruby 1.8中,一方面proc/lambda和另一方面Proc.new
之间存在细微的差异.
In Ruby 1.8, there are subtle differences between proc/lambda on the one hand, and Proc.new
on the other.
- 这些区别是什么?
- 您能提供有关如何决定选择哪一个的指南吗?
- 在Ruby 1.9中,proc和lambda是不同的.怎么了?
推荐答案
使用lambda
创建的proc和使用Proc.new
创建的proc之间的另一个重要但细微的区别是它们如何处理return
语句:
Another important but subtle difference between procs created with lambda
and procs created with Proc.new
is how they handle the return
statement:
- 在
lambda
创建的proc中,return
语句仅从proc本身返回 - 在
Proc.new
创建的proc中,return
语句有点令人惊讶:它不仅从proc,而且还从封装proc的方法中返回控制!
- In a
lambda
-created proc, thereturn
statement returns only from the proc itself - In a
Proc.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!
这里是lambda
创建的proc的return
的作用.它的行为可能与您预期的一样:
Here's lambda
-created proc's return
in action. It behaves in a way that you probably expect:
def whowouldwin
mylambda = lambda {return "Freddy"}
mylambda.call
# mylambda gets called and returns "Freddy", and execution
# continues on the next line
return "Jason"
end
whowouldwin
#=> "Jason"
现在这是一个Proc.new
创建的proc的return
在做同样的事情.您将看到以下其中一种情况,其中Ruby打破了广受赞誉的最小惊喜原则":
Now here's a Proc.new
-created proc's return
doing the same thing. You're about to see one of those cases where Ruby breaks the much-vaunted Principle of Least Surprise:
def whowouldwin2
myproc = Proc.new {return "Freddy"}
myproc.call
# myproc gets called and returns "Freddy",
# but also returns control from whowhouldwin2!
# The line below *never* gets executed.
return "Jason"
end
whowouldwin2
#=> "Freddy"
由于这种令人惊讶的行为(以及更少的键入),在制作proc时,我倾向于使用lambda
而不是Proc.new
.
Thanks to this surprising behavior (as well as less typing), I tend to favor using lambda
over Proc.new
when making procs.
这篇关于何时使用lambda,何时使用Proc.new?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!