macsig macsig - 1 year ago 92
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)


Answer Source

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

  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.

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