Ruby Lambda

If you've ever programmed in Ruby and have come across either a proc or a lambda, you might have been wondering what the difference is between the two and when you would use one over the other. This article will try to explain the difference between the two in order to give you a better idea of what they are in the hope that if you know a bit more about them you will begin to understand their respective uses. My feeling is that if you don't understand what you're doing or what you're using, you won't code as efficiently or as effectively.

Ruby contains these neat little things called a Lambda. It's actually a borrowed concept and name from Python, a language that has a lot of influence in Ruby's design.

These Lambda functions have different names in other languages, such as:

Anonymous Function
They essentially name the same concept, so if you're coming from another language that has these, you already have a head start.

In Ruby, a Lambda is defined as follows,
x = lambda { return "ar har har har" }

Open in new window

If you're not new to Ruby, you've probably heard of procs. These are very similar to lambdas with very subtle, yet significant, differences. The most notable difference between a proc and a lambda is that returning from a proc will actually return from the method its defined within.  Example:
def a_meth
                         proc ={ return "blah" }
                         return "not reached"

Open in new window

If you run this in IRB, you'll get "blah" returned instead of "not reached".  Now let's look at a similar method using a lambda:
def a_new_meth
                         lam = lambda{ return "yeeee hah" }
                         return "not the lambda"

Open in new window

The output is "not the lambda"; that is, unlike, does not force an immediate exit from the enclosing block.

As you can see, lambdas are real anonymous functions whereas procs are just self contained processes that can be run. Thus, if you want the result returned from the lambda, you would need to either use puts for output or store the result in a variable for later use.

Another note about lambdas and arity (arguments), they should be treated as if they are a function.  If you define this lambda:
 > x = lambda { |x, y| puts x + y } 

Open in new window

and call it like so,
 >, 2, 3) 

Open in new window

you will get a "wrong number of arguments" error.

A proc will not throw that error.  It will simply accept the first two arguments, run the function according to them, and ignore the extras.  For example:
 p ={|x,y| puts x + y}

Open in new window

That'll return the expected number 3, which is the sum of the first two arguments passed into the function

Thanks for reading and good luck in your ruby ninjutsu adventures :)

Comments (0)

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.