Rixiform Inc.

Proc.new, lambda, and proc

June 18th 2008

In response to the harmony of thought posting on good ruby interview questions I wrote the following (posted here for interest and to preserve formatting)…

One thing about lambdas and procs. Even though they appear to be the same class they do not behave completely the same. From running my_lambda.inspect and seeing the Proc instance you would never guess it but they are different.

Essentially lambda and Proc.new handle arguments and the “return” statement differently. Also the “proc” method returns a lambda not a Proc.

Here’s some code to prove the point. The argument handling is the easiest to demo:

my_proc = Proc.new {|x,y| print x,y}
my_lambda = lambda {|x,y| print x,y}
my_other_proc = proc {|x,y| print x,y}

# pass in one variable instead of 2
my_proc.call(1) #this doesn't throw an error and sets y to nil
my_lambda.call(1) #this throws an error
my_other_proc.call(1) #this throws an error like a lambda because it actually is a lambda not a proc in ruby 1.8.6

Also in Ruby 1.9 I think that the “proc” method (as seen in line three) will actually return a Proc and not a lambda. Ruby 1.9 will also add a “lambda?” method for you to clarify the difference between a Proc and a lambda.

O’Reilly’s book “The Ruby Programming Language” by Matz (Yukihiro Matsumoto) and David Flanagen has a great chapter on this.