DEV Community

OKURA Masafumi
OKURA Masafumi

Posted on

Ruby: proc and lambda

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.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay