Difference between proc and lambda in ruby

One of the core concepts about Ruby that a programmer should remember is that blocks are not objects. It is possible to convert them into objects by wrapping them inside the “Proc” class instance. The “Proc” and “Lambda” classes are probably the most awesome aspects of Ruby and need to be used well in order to get the desired results. Not much of knowledge is available on how to use Procs and Lambdas and what the differences between both are. I’d like to take a stab at how we can differentiate between Procs and Lambdas with a couple of thoughts below.

1. Proc doesn’t check the parameters passed, but Lambda does

> proc1 = Proc.new { |a, b| a + 5 }

> proc1.call(2)      # call with only one parameter
=> 7                    # no error, unless the block uses the 2nd parameter

  
> lambda1 = lambda { |a, b| a + 5 }

> lambda1.call(2)
ArgumentError: wrong number of arguments (1 for 2)


Proc will throw error only if the block uses the second param.

> proc2 = Proc.new { |a, b| a + b }

> proc2.call(2)      # call with only one parameter
TypeError: nil can’t be coerced into Fixnum

 2. Proc returns from the calling method, while Lambda doesn’t

> def meth1
>   Proc.new { return ‘return from proc’ }.call
>   return ‘return from method’
> end

> puts meth1
return from proc

> def meth2
>   lambda { return ‘return from lambda’ }.call
>   return ‘return from method’
> end

> puts meth2
return from method

If they are not called inside a method,
 
> proc1 = Proc.new { return “Thank you” }

> proc1.call
 
LocalJumpError: unexpected return


> lambda1 = lambda { return “Thank you” }
 

> lambda1.call

=> “Thank you”

Santhosh Kattissery is a senior consultant at Compassites. He is a web developer with hands on experience in all phases of development, from requirements gathering, database design, development, testing and deployment. He specializes in open source technologies like Ruby on Rails, JQuery, Mongodb & MySql. Prior to Compassites he has worked as a contractor for internet giants like Google and LinkedIn.

Leave a comment