Stoic Stoic - 1 year ago 61
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
method's yield to
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(&:calc) # this won't work I know, but still is more readable to me

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download