Proc vs Lambda Differences
In this page:
Proc vs Lambda Differences
The two key differences are argument strictness (a lambda raises ArgumentError on the wrong argument count, a Proc does not) and return behavior (a lambda's return exits just the lambda, while a Proc's return exits the enclosing method entirely, which can cause surprising control flow). Because of this, lambdas are usually the safer default choice. .lambda? on a Proc object tells you which kind it actually is.
Warning: A return inside a Proc (not a lambda) exits the enclosing method entirely -- this is a common source of confusing bugs.
Example: Proc vs Lambda Differences
strict_lambda = lambda { |x, y| x + y }
lenient_proc = Proc.new { |x, y| (x || 0) + (y || 0) }
begin
strict_lambda.call(1)
rescue ArgumentError => e
puts "Lambda raised: #{e.class}"
end
puts lenient_proc.call(1) # no error, y is nil -> treated as 0
puts strict_lambda.lambda?
puts lenient_proc.lambda?
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: