Posts

Showing posts from September, 2012

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 …