Possible Duplicate:
What's the difference between a proc and a lambda in 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 that I get is as follows:
The result of running func_one is 123
The result of running func_two is 456
As for func_two
, where is the the value of the first return
, that is, 123
?
Thanks.
This is one of the main differences between Procs and lambdas.
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.
Read on Procs v. lambdas here: http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Method_Calls
See duplicate SO question: Why does explicit return make a difference in a Proc?
EDIT:
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
...