1

Say I have a method that needs three arguments:

def foo(a, b, c)
end

And I have said arguments in an array:

[a, b, c]

Is there a trivial or one method way of using the array as the arguments, like:

foo(array.some_method)

2 Answers 2

5

You can use the splat operator:

foo(*array)
Sign up to request clarification or add additional context in comments.

4 Comments

Does the splat operator have to be in the method's definition? I am trying to use a library class method, so I can't alter the signature of the method.
No, it's a way of 'exploding' an array to match an existing method signature, so in your example you can use it without altering your foo method
You're right. Although the code that results its fairly funkified: Date.valid_date?(*'9666-96-96'.split('-').map(&:to_i)). I probably should make it into two steps.
Looks indeed like an ugly oneliner :)
4
def foo(*bar)

end

Foo now exacts an array as parameters. You could also make it accept a hash by doing

def foo(bar={})

end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.