Forum: Ruby 1.9 -> lambda syntax with &

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
05be5d6610e2c3f1780aa0e39e902e93?d=identicon&s=25 Farrel Lifson (Guest)
on 2008-11-18 10:29
(Received via mailing list)
Given
  sum = Proc.new{|sum,num| sum + num}
is
  sum2 =  ->(a,b) &sum
valid syntax? Or is
  sum2 = ->(a,b,&sum)
correct?

Farrel
753dcb78b3a3651127665da4bed3c782?d=identicon&s=25 Brian Candler (candlerb)
on 2008-11-18 10:51
Farrel Lifson wrote:
> Given
>   sum = Proc.new{|sum,num| sum + num}
> is
>   sum2 =  ->(a,b) &sum
> valid syntax? Or is
>   sum2 = ->(a,b,&sum)
> correct?

It's not clear to me what you're trying to do.

If you are defining a lambda by means of an existing block, then that
existing block will already have a parameter list, so you don't specify
it again. That is:

irb(main):001:0> sum = Proc.new{|sum,num| sum + num}
=> #<Proc:0x83a5a18@(irb):1>
irb(main):002:0> sum2 = lambda(&sum)
=> #<Proc:0x83a5a18@(irb):1>
irb(main):003:0> sum2[3,4]
=> 7

It appears that the -> syntax can't be used here.

However, if you want to define a new lambda which takes a block as an
argument, then you need to give a body for the new lambda.

irb(main):004:0> sum2 = ->(a,b,&foo) { foo[a,b] + 9 }
=> #<Proc:0x838310c@(irb):4 (lambda)>
irb(main):005:0> sum2[3,4,&sum]
=> 16
This topic is locked and can not be replied to.