1.9 -> lambda syntax with &

F

Farrel Lifson

Given
sum = Proc.new{|sum,num| sum + num}
is
sum2 = ->(a,b) &sum
valid syntax? Or is
sum2 = ->(a,b,&sum)
correct?

Farrel
 
B

Brian Candler

Farrel said:
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
 

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,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top