Ruby - lambda vs. Proc.new [duplicate] Ruby - lambda vs. Proc.new [duplicate] ruby ruby

Ruby - lambda vs. Proc.new [duplicate]


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 end1> begin; Proc.new { return 1 }.call endLocalJumpError: unexpected return...


In the proc, the return "123" is bubbling up and returning from the outer function, func_one. Therefore the second return statement is never encountered.

In the lambda, the return "123" is returning only from the lambda. You're not setting an variable to the return value of the lambda (when you do lambda_new.call, so the value is basically just thrown out. Then, the return "456" is called and returns from the function. If, instead of returning "456", you returned lambda_new.call, the return value of func_two would be "123".


123 is a value of lambda_new.call statement, but it is not used and not shows up.