0

I have an array of the arguments that a function is taking, the length of the array can change.

i want to call the function with the amount of arguments that the array have, how can i do this in ruby.

The array can have a lot of arguments so some kind of a if/case statement would not work.

array = ["one","two","tree","four", "five"]

def callFunction(a)
    callAnotherFunction(a[0],a[1],a[2],a[3],a[4])
end

I want to use some kind of a loop to send the correct amount of parameters. the callAnotherFunction function should be called with the amount of arguments that the array have. the array will always have the correct amount of arguments.

Lasse Sviland
  • 1,479
  • 11
  • 23

2 Answers2

2

You can use the splat operator.

def callFunction(a)
  callAnotherFunction(*a)
end

See: http://ruby-doc.org/core-2.1.3/doc/syntax/calling_methods_rdoc.html

ihaztehcodez
  • 2,123
  • 15
  • 29
0
def add(*arr)    # The * slurps multiple arguments into one array
  p arr          # => [1, 2, 3]
  arr.inject(:+)
end

p add(1,2,3)     # => 6

def starts_with_any_of(str, arr)
  str.start_with?(*arr)  # start_with? does not take an array, it needs one or more strings
                         # the * works in reverse here: it splats an array into multiple arguments
end

p starts_with_any_of("demonstration", ["pre", "post", "demo"])  # => true
steenslag
  • 79,051
  • 16
  • 138
  • 171