Lambda and a Proc

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

There is a great description of the differences on wikipedia:

http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Method_Calls#Understanding_blocks.2C_Procs_and_methods

Give that a read.

Ben

···

On Wed, Jun 17, 2009 at 7:15 PM, aidy <aidy.lewis@googlemail.com> wrote:

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

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.

···

On Wed, Jun 17, 2009 at 2:15 PM, aidy<aidy.lewis@googlemail.com> wrote:

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

--
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