tfboy
tfboy

Reputation: 947

How to wrap a method that takes variable-length arguments?

Suppose there's a method called foo that takes variable-length arguments.

def foo(*args)
  # Implementation omitted
end

And I want to wrap the method with bar.

def bar(*args)
# Will call `foo` at some point
# `foo(args)` isn't satisfactory.
end

How do I call foo inside bar so that if I call bar with bar(1,2,3), foo(1,2,3) is also called?

Some constraints are:

  1. I could not change the code for foo.
  2. foo and bar should have exactly the same signature.

Of course I could do foo(args) inside bar. But if that's the case, for foo, what it will receive is an Array of Array instead of an Array.

Thanks.

Upvotes: 2

Views: 129

Answers (1)

falsetru
falsetru

Reputation: 369494

Use a splat operator (*) as Blender commented: It converts an array into arguments.

def bar(*args)
  foo(*args)
end

Upvotes: 2

Related Questions