What is the Difference Between Procs and Lambdas in Ruby?
Now that we've seen procs and lambdas, we are going to see their differences in this lesson. There are two key differences, other than the syntax. But, they are so tiny that you may never even notice them while programming. Still, it's good to know.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

Now that we've seen Procs and Lambdas I think it's important to clarify the difference between the two. There are two key differences in addition to the syntax. Please note that the differences are subtle, even to the point that you may never even notice them while programming. Still, they're good to know, especially if you plan on building advanced programs.

Argument Count

The first key difference is that Lambdas count the arguments you pass to them whereas Procs do not. For example,

full_name = lambda { |first, last| first + " " + last} 
p full_name.call("Jordan", "Hudgens")

Running this code will work properly. However if I pass another argument like this:

p full_name.call("Jordan", "David", "Hudgens")

The application throws an error saying that we're passing in the wrong number of arguments.

large

Now, let's see what happens with Procs:

full_name = Proc.new{ |first, last| first + " " + last} 
p full_name.call("Jordan", "David", "Hudgens")

If you run this code you can see that it does not throw an error. It simply looks at the first two arguments and ignores anything after that.

large

In review, Lambdas count the arguments passed to them whereas Procs don't.

Return behavior

Secondly, Lambdas and Procs have different behavior when it comes to returning values from methods. To see this, I'm going to create a method called my_method.

def my_method
  x = lambda  {return}
  x.call
  p "Text within the method"
end

my_method

If I run this method, it prints out "Text within the method".

large

Now, let's try the exact same implementation with a Proc.

def my_method
  x = Proc.new {return}
  x.call
  p "Text within the method"
end

my_method

When you run it this time, it returns a value of nil.

large

What happened is that when the Proc saw the word return it exited out of the entire method and returned a nil value. However, in the case of the Lambda it processed the remaining part of the method.

So, these are the subtle and yet important differences between Lambdas and Procs.