lambda and a Proc

A

aidy

Hi,

I am a bit unsure on what the difference is between a lambda and a
Proc?

hello = lambda { puts('aidy, aidy, aidy' ) }
hello.call

hello = Proc.new{ puts('aidy, aidy, aidy' ) }
hello.call

Cheers

Aidy
 
R

Rick DeNatale

Hi,

I am a bit unsure on what the difference is between a lambda and a
Proc?

hello = lambda { puts('aidy, aidy, aidy' ) }
hello.call

hello = Proc.new{ puts('aidy, aidy, aidy' ) }
hello.call

Well no differences that affect the above code, but

a return in a lambda block causes the block to evaluate to the value
of the return, in a proc block it causes a return from the method
where the block was created.
rb(main):011:0> def foo_lambda
irb(main):012:1> lambda {return 42}
irb(main):013:1> end
=> nil
irb(main):015:0> foo_lambda.call
=> 42

irb(main):028:0> def bar_lambda
irb(main):029:1> p = lambda {return 42}
irb(main):030:1> puts "calling p #{p.call}"
irb(main):031:1> puts "back from call"
irb(main):032:1> p
irb(main):033:1> end
=> nil
irb(main):034:0> bar_lambda.call
calling p 42
back from call
=> 42


irb(main):005:0> def bar
irb(main):006:1> p = Proc.new {return 42}
irb(main):007:1> p.call
irb(main):008:1> puts "after call"
irb(main):009:1> end
=> nil
irb(main):010:0> bar
=> 42

rb(main):001:0> def foo
irb(main):002:1> Proc.new {return 42}
irb(main):003:1> end
=> nil
irb(main):004:0> foo.call
LocalJumpError: unexpected return
from (irb):2:in `foo'
from (irb):4:in `call'
from (irb):4

And in Ruby 1.9 lambdas raise an ArgumentError when called with the
wrong number of arguments, a Proc will set missing arguments to nil,
and ignore extra arguments.

The way I think of this is that lambdas act more like nameless methods.

--
Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Twitter: http://twitter.com/RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top