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 instances of Proc
Proc.new {}.inspect # #<Proc:0x007f9ab7990440@-e:1>
-> {}.inspect # #<Proc:0x007fa71d0a86a8@-e:1 (lambda)>
Rigid argument handling
lambdas
are strict on argument numbers. 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) ArgumentErrorirb> ->(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."
endirb> lambda_returnBefore 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."
endirb> 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.
Ruby Mastery
We’re currently finalizing our first online course: Ruby Mastery.
Join the list for an exclusive release alert! 🔔
Also, you can follow us on x.com as we’re very active on this platform. Indeed, we post elaborate code examples every day.
💚