什么是proc和lambda?请实际例子 [英] what are procs and lambdas? practical examples please

查看:65
本文介绍了什么是proc和lambda?请实际例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
何时使用lambda,何时使用Proc.new?

Possible Duplicate:
When to use lambda, when to use Proc.new?

(我知道有人问过几次,但我找不到满意的答案)有人可以解释一下Blocks,Procs和Lambdas以及为什么一个应该与另一个一起使用,一个人应该使用proc的情况是什么,类似和/或lambda.也对计算机内存有影响.请提供实际示例.

(I know it had been asked several times but I couldn't find satisfactory answer)Can somebody please explain Blocks, Procs and Lambdas and why one should be used over other, what are the situation when one should use proc, similar and/or lambda. Also there effect on computer memory. Practical examples please.

推荐答案

尝试克里斯·派恩(Chris Pine)学习编程.

要获得更多基础知识,建议您阅读为什么要为Ruby编写(辛辣的)指南 .本指南负责创建当今许多Ruby's Pro!确保看看!

For more foundation I suggest you read Why’s (poignant) Guide to Ruby. This guide is responsible for creating many of nowadays Ruby's Pro! Make sure to take a look!

Joey deVilla

Explanation by Joey deVilla

另一个重要但细微的区别是使用lambda创建的proc和使用Proc.new创建的proc处理return语句的方式:

Another important but subtle difference is in the way procs created with lambda and procs created with Proc.new 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 behaviour (as well as less typing), I tend to favour using lambda over Proc.new when making procs.

这篇关于什么是proc和lambda?请实际例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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