Arity difference between Lambda and Proc in Ruby
Many devs think Procs & Lambas in Ruby are interchangable... and it a lot of cases they can be.
However I did come across a difference to be aware of.
Procs do not enforce arity where a Lambda will.
Let's take a look at a Proc's behavior:
# Argument provided
p = Proc.new { |arg| puts arg }
p.call("TEST")
TEST
=> nil
# No argument provided
p = Proc.new { |arg| puts arg }
p.call
=> nil
Now let's look at lambdas:
# Argument provided
l = ->(arg) { puts arg }
l.call("TEST")
TEST
=> nil
# No argument provided
l = ->(arg) { puts arg }
l.call
=> wrong number of arguments (given 0, expected 1) (ArgumentError)
See how there is strict arity on a lambda where the proc will not complain.
Tweet