Ruby - lambda 与 Proc.new [英] Ruby - lambda vs. Proc.new
问题描述
可能重复:
proc和lambda有什么区别红宝石?
当运行这个 Ruby
代码时:
When run this Ruby
code:
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
,firstreturn
的值在哪里,即123
?
As for func_two
, where is the the value of the first return
, that is, 123
?
谢谢.
推荐答案
这是 Procs 和 lambdas 之间的主要区别之一.
This is one of the main differences between Procs and lambdas.
Proc 中的 return 从其封闭的块/方法返回,而 lambda 中的 return 只是从 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屋!