何时使用lambda,何时使用Proc.new? [英] When to use lambda, when to use Proc.new?

查看:72
本文介绍了何时使用lambda,何时使用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, the return statement returns only from the proc itself
  • In a Proc.new-created proc, the return 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆