ruby convert array into function arguments

RubyArraysFunctionArguments

Ruby Problem Overview


Say I have an array. I wish to pass the array to a function. The function, however, expects two arguments. Is there a way to on the fly convert the array into 2 arguments? For example:

a = [0,1,2,3,4]
b = [2,3]
a.slice(b)

Would yield an error in Ruby. I need to input a.slice(b[0],b[1]) I am looking for something more elegant, as in a.slice(foo.bar(b)) Thanks.

Ruby Solutions


Solution 1 - Ruby

You can turn an Array into an argument list with the * (or "splat") operator:

a = [0, 1, 2, 3, 4] # => [0, 1, 2, 3, 4]
b = [2, 3] # => [2, 3]
a.slice(*b) # => [2, 3, 4]
Reference:

Solution 2 - Ruby

Use this

a.slice(*b)

It's called the splat operator

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1134991View Question on Stackoverflow
Solution 1 - RubyJohnsywebView Answer on Stackoverflow
Solution 2 - RubySergio TulentsevView Answer on Stackoverflow