vendredi 8 mai 2015

Ruby Closures: How to return args and block as a single argument to pass to a method

Suppose I have a method that takes args and a block:

def yield_if_widget(*args, &block)
  if args[0].is_a?(Widget)
    block.call
  end
end

I can call this method with arguments and a block:

yield_if_widget(Widget.new) do
  puts "I like widgets"
end

But what if I have another method that prepares the arguments and the block:

def widget_and_block
  args = [Widget.new]
  block = proc{ puts "I like widgets" }

  [args, block]
end

And I want to be able to pass it directly to the first method:

yield_if_widget(*widget_and_block)

Is this possible? How? Assume that yield_if_widget is defined in a library and monkey-patching it is not an option.

Aucun commentaire:

Enregistrer un commentaire