Ruby: difference between proc and lambda

A proc and a lambda are very similar except:

1. they handle arguments differently

proc {} 

and

Proc.new {}

are equivalent.

However, using lambda {} gives you a proc that checks the number of arguments passed to it.

See: 

http://www.ruby-doc.org/core-2.0/Kernel.html#method-i-lambda

and:

http://stackoverflow.com/questions/1740046/whats-the-difference-between-a-proc-and-a-lambda-in-ruby

2. they handle return and break statements differently

def bar 

f = lambda { return “from inside lambda”}

f.call

return “return from bar”

end

puts bar

def foo

f = Proc.new { return “from inside proc”}

f.call

return “return from foo”

end

puts foo

gives:

return from bar

from inside proc

See

http://www.akshay.cc/blog/2010-02-14-control-flow-differences-between-ruby-procs-and-lambdas.html

and

http://www.slideshare.net/MatthieuSegret/ruby-block-proc-and-lambda

Note that the behaviour of proc and lambda changed between Ruby 1.8 and Ruby 1.9 (and therefore 2.0). 

In 1.8, they were identical (both had lambda semantics). 

proc was like lambda in 1.8. However, it’s like Proc.new in 1.9

See also this post which summarises the difference as follows:

“In short: lambdas behave like methods, non-lambda Procs behave like blocks.”

http://stackoverflow.com/questions/4799964/differences-between-proc-and-lambda-in-ruby

 

Leave a Reply

Your email address will not be published. Required fields are marked *