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

查看:35
本文介绍了何时使用 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 创建的 procs 和使用 Proc.new 创建的 procs 之间的另一个重要但细微的区别是如何他们处理 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 创建的过程中,return 语句仅从过程本身返回
  • 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-created 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-created 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"

由于这种令人惊讶的行为(以及更少的输入),我倾向于在制作过程时使用 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天全站免登陆