ruby convert array into function arguments
47,607
Solution 1
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
Use this
a.slice(*b)
It's called the splat operator
Related videos on Youtube
Author by
user1134991
Updated on July 08, 2022Comments
-
user1134991 almost 2 years
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 ina.slice(foo.bar(b))
Thanks.-
totymedli almost 6 yearsSame question: Sending elements of an array as arguments to a method call
-