Wednesday, December 17, 2008

difference between lambda and Proc.new (Closures)

The #lambda is not the same as Proc#new. It’s ok to say the same, but not exactly.
1: First Difference
$ irb irb(main):001:0>
Proc.new{|x,y| }.call 1,2,3
=>
nil


irb(main):002:0>
lambda {|x,y| }.call 1,2,3

ArgumentError: wrong number of arguments (3 for 2) from (irb):2 from (irb):2:in `call' from (irb):2 from :0
irb(main):003:0>

2: Second Difference
def test_ret_procnew
ret = Proc.new { return 'Returned' }
ret.call “This is not reached”
end
# prints 'Returned'
puts test_ret_procnew


While return from lambda acts more conventionally, returning to its caller:

def test_ret_lambda
ret = lambda { return “Returned” }
ret.call
“This is printed”
end
# prints “This is printed”

puts test_ret_lambda