DEV Community

loading...

Ruby: proc and lambda

okuramasafumi profile image OKURA Masafumi ・1 min read

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)
Enter fullscreen mode Exit fullscreen mode

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.

Procs behave like blocks, and lambdas behave like methods. When used with methods such as each, which are usually used with blocks, it might be a good idea to use procs instead of lambdas.

Discussion (0)

pic
Editor guide