Proc vs Lambda in Ruby

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

  • rigid argument handling
  • return in procs and lambdas

Introduction

They are both instance of Proc

Proc.new {}.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> Proc.new {|arg1, arg2| puts "args: #{arg1}, #{arg2}"}.call(1)
=> args: 1,
irb> Proc.new do |arg1, arg2|
puts "args: #{arg1}, #{arg2}"
end.call(1,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."
end
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."
Proc.new {return}.call
puts "After proc call."
end
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: www.rubycademy.com


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 .