Procs , Lambda and their difference

Procs 

Like variables hold data, procs hold the code itself.
example_proc = Proc.new{ puts “I am a Example” }
We will use proc by using .call method
example_proc.call
lambda { foo } and proc { foo } is essensially the same thing, you can use both interchangeable in your code.

There are couple of differences which are as follows

One of the main difference and major difference between them is that  Proc object does not care at all for the number of arguments you pass to it e.g.

p = proc{|a,b| p "The value of a is #{a.inspect}. The value of b is #{b.inspect}"}
 
p.call 1,2
# => "The value of a is 1. The value of b is 2"
 
p.call 1
# => "The value of a is 1. The value of b is nil"
 
p.call 1,[2,3],Class.new
# => "The value of a is 1. The value of b is [2,3]"
 
So , it takes the first two arguments and discards the rest but if we pass  less than two it will assume that the other(s) are nil

l = lambda{|a,b| p "The value of a is #{a.inspect}. The value of b is #{b.inspect}"}
 
l.call 1,2
# => "The value of a is 1. The value of b is 2"
 
l.call 1
# => ArgumentError: wrong number of arguments (1 for 2)
#       from (irb):74:in `block in irb_binding'
#       from (irb):75:in `call'
#       from (irb):75
 
l.call [2,3],1,3
# => ArgumentError: wrong number of arguments (3 for 2)
#       from (irb):74:in `block in irb_binding'
#       from (irb):75:in `call'
#       from (irb):75
 
 
As you can see lambda is very strict about it’s number of arguments. I can’t give it neither more or less arguments than those specified the time it was defined.

This is why many believe that using lambda instead of proc is preferable because you don’t want to silently ignore the argument mismatching.

 But if you do want that kind of behaviour you should go ahead and use the proc instead.

Comments

Popular posts from this blog

Inserting and Moving elements inside Ruby Array

Interview Question on Ruby on Rails