Proc vs Lambda Differences
Procs and lambdas look alike but act differently: a lambda is strict about its inputs and returns only from itself, while a proc is relaxed. It is like a serious clerk versus a laid-back helper.
In this page:
Syntax
my_proc = Proc.new { |a, b| expression } # lenient arguments
my_lambda = ->(a, b) { expression } # strict arguments
# return exits the method in a proc, only the lambda in a lambda
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Expecting
returnin a Proc and a lambda to behave the same, when a lambda returns from itself and a Proc returns from the enclosing method. - Assuming a Proc raises an error for missing arguments, when it fills them with
nil. - Choosing a Proc for a strict function, when a lambda checks the argument count.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: