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.

3
  • Is there a maximum size to the array? and is that maximum size a reasonable number? Commented Nov 5, 2015 at 21:06
  • well in general i want it to be scalable, but i believe it will always be between 2 and 15 Commented Nov 5, 2015 at 21:09
  • Duplicate? stackoverflow.com/q/918449/2988 Commented Nov 6, 2015 at 10:52

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

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.