← Back to Ruby Course | Chapter 8: Blocks, Procs & Lambdas | Lesson 5 of 6

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.
Syntax
ruby
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

markup
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?
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
  1. Expecting return in a Proc and a lambda to behave the same, when a lambda returns from itself and a Proc returns from the enclosing method.
  2. Assuming a Proc raises an error for missing arguments, when it fills them with nil.
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.