Ruby-Lambda与Proc.new [英] Ruby - lambda vs. Proc.new

查看:52
本文介绍了Ruby-Lambda与Proc.new的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
露比吗?

在运行以下 Ruby 代码时:

def func_one
    proc_new = Proc.new {return "123"}
    proc_new.call
    return "456"
end

def func_two
    lambda_new = lambda {return "123"}
    lambda_new.call
    return "456"
end

puts "The result of running func_one is " + func_one
puts ""
puts "The result of running func_two is " + func_two

我得到的结果如下:

The result of running func_one is 123

The result of running func_two is 456

关于 func_two 第一返回 123 的值在哪里?

As for func_two, where is the the value of the first return, that is, 123?

谢谢.

推荐答案

这是Procs和lambda之间的主要区别之一.

This is one of the main differences between Procs and lambdas.

Proc中的返回从其所在的块/方法返回,而lambda中的返回仅从lambda中返回.当您在func_two内部调用lambda时,它只是简单地将其值返回原位,而不保存.

A return in a Proc returns from its enclosing block/method, while a return in a lambda simply returns from the lambda. When you call the lambda inside the func_two, it simply returns its value in place, which is not saved.

在此处阅读Procs v.lambdas: http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Method_Calls

Read on Procs v. lambdas here: http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Method_Calls

查看重复的SO问题:为什么显式返回在Proc中有所作为?

See duplicate SO question: Why does explicit return make a difference in a Proc?

要进一步说明这种差异,请将func_one和func_two交换为块,然后看看会发生什么:

To further illustrate this difference, swap func_one and func_two for blocks and see what happens:

> begin; lambda { return 1 }.call end
1
> begin; Proc.new { return 1 }.call end
LocalJumpError: unexpected return
...

这篇关于Ruby-Lambda与Proc.new的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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