Sim*_*ity 39 ruby lambda return proc-object
可能重复:
Ruby中的proc和lambda有什么区别?
运行此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
Run Code Online (Sandbox Code Playgroud)
我得到的结果如下:
The result of running func_one is 123
The result of running func_two is 456
Run Code Online (Sandbox Code Playgroud)
至于func_two,第一个 的价值在哪里return,也就是说,123?
谢谢.
num*_*407 28
这是Procs和lambdas之间的主要区别之一.
Proc中的返回从其封闭块/方法返回,而lambda中的返回仅从lambda返回.当你在func_two中调用lambda时,它只是返回它的值,而不是保存它.
请阅读Procs v.lambdas:http: //en.wikibooks.org/wiki/Ruby_Programming/Syntax/Method_Calls
请参阅重复的SO问题: 为什么显式返回会在Proc中产生影响?
编辑:
为了进一步说明这种差异,请将func_one和func_two换成块,看看会发生什么:
> begin; lambda { return 1 }.call end
1
> begin; Proc.new { return 1 }.call end
LocalJumpError: unexpected return
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34505 次 |
| 最近记录: |