macsig macsig - 1 month ago 6
Ruby Question

Passing a block as keyword argument

Is it possible (if yes how) to pass a block as a keyword argument in a ruby method?

Basically, I'd like to do

pippo(even: {|n| n+1 }, odd: {|n| n-1})


Having the method defined as such

def pippo(even: , odd:)
even? ? even.yield(self) : odd.yield(self)
end


Thanks

Answer

If you want to supply multiple blocks you need to pass them through as a Proc, or use the lambda construct to declare them:

when(
  even: -> (x) { x+1 },
  odd: -> (x) { x-1 }
)

You can also declare them using proc { ... } or lambda { ... } which is the old style declaration for same.

Comments