Stoic Stoic - 1 month ago 5
Ruby Question

Passing all Parameters from method to a block

I have a Ruby method and a block configured as below:

def control; yield(1,2,3); end
calc = -> (a,b,c) { a + b+ c }


Now, I want to pass all the params from the
control
method's yield to
calc
block, like this:

control{|a,b,c| calc[a,b,c]}
control{|*args| calc[*args]} # another succint way to write that.
# => 6


Is there a more readable way/syntax to write the same? Probably, like the following:

control.passthru(:calc)
control(&:calc) # this won't work I know, but still is more readable to me
control.yield[calc]
calc.call(*control.yielded_params)

Answer

I am not sure why do you think it’s more readable, but here you go:

control &calc
#⇒ 6

control(&:calc) is not working because it calls Symbol#to_proc on :calc symbol. You are likely want to pass the λ ⇒ pass it directly.