Example
hash = {foo: :bar}
nested_array = [[1, 2]]
proc_printer = Proc.new {|a, b| puts "a: #{a}, b: #{b}" }
lambda_printer = lambda {|a, b| puts "a: #{a}, b: #{b}" }
hash.each(&proc_printer) # => a: foo, b: bar
nested_array.each(&proc_printer) # => a: 1, b: 2
hash.each(&lambda_printer) # => a: foo, b: bar
nested_array.each(&lambda_printer) # => wrong number of arguments (given 1, expected 2) (ArgumentError)
What happened?
A lambda
takes argument differently than a proc
does. In this case, an array in nested array case "gets extracted" into two arguments with a proc
, while it is passes as one array with a lambda
.
Proc
s behave like blocks, and lambda
s behave like methods. When used with methods such as each
, which are usually used with blocks, it might be a good idea to use proc
s instead of lambda
s.
Top comments (0)