Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby convert array into function arguments

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.

like image 301
user1134991 Avatar asked Feb 19 '13 13:02

user1134991


People also ask

How do you take an array as an argument in Ruby?

It is also possible to pass an array as an argument to a method. For example, you might want a method that calculates the average of all the numbers in an array. Your main program might look like this: data = [3.5, 4.7, 8.6, 2.9] average = get_average(data) puts "The average is #{average}."

What is array in Ruby?

Ruby arrays are ordered, integer-indexed collections of any object. Each element in an array is associated with and referred to by an index. Array indexing starts at 0, as in C or Java.


1 Answers

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:

  • Array to Arguments Conversion
like image 162
Johnsyweb Avatar answered Sep 25 '22 12:09

Johnsyweb