Proc vs Lambda in Ruby

in this article, we’re going to explore the following topics:

  • rigid argument handling
  • return in procs and lambdas


They are both instance of Proc {}.inspect # #<Proc:0x007f9ab7990440@-e:1>
-> {}.inspect # #<Proc:0x007fa71d0a86a8@-e:1 (lambda)>

Rigid argument handling

lambdas are strict on argument number. If the call doesn’t respect the exact number of arguments then an ArgumentError is raised

irb> ->(arg1, arg2) {}.call(1)
wrong number of arguments (given 1, expected 2) ArgumentError
irb> ->(arg1, arg2) {}.call(1,2,3)
wrong number of arguments (given 3, expected 2) ArgumentError

Otherwise, Procs are flexible about argument handling

irb> {|arg1, arg2| puts "args: #{arg1}, #{arg2}"}.call(1)
=> args: 1,
irb> do |arg1, arg2|
puts "args: #{arg1}, #{arg2}",2,3)
=> args: 1, 2

Return in procs and lambdas

Using return in a lambda returns out of the lambda scope

def lambda_return
puts "Before lambda call."
lambda {return}.call
puts "After lambda call."
irb> lambda_return
Before lambda call.
After lambda call.

Otherwise, using return in a proc returns out of the proc ‘s calling scope

def proc_return
puts "Before proc call." {return}.call
puts "After proc call."
irb> proc_return
Before proc call.

In proc_return , the return statement returns out of the calling scope (which is proc_return method). So the second puts is never called.

Voilà !

May I have your attention please 🎤🎤

Feel free to subscribe here:

Thank you for taking the time to read this post :-)

Feel free to 👏 and share this Medium post if it has been useful for you.

Here is a link to my last medium post: Display Complex Objects .