Sending elements of an array as arguments to a method call

ruby, ruby-on-rails

Solution

try calling it like this

hello(arr1, *arr2)

here's a run through in irb

irb(main):002:0> def hello(foo, *bar)
irb(main):003:1>   puts foo.inspect
irb(main):004:1>   puts bar.inspect
irb(main):005:1> end
=> nil
irb(main):006:0> arr1 = ['baz', 'stuff']
=> ["baz", "stuff"]
irb(main):007:0> arr2 = ['ding', 'dong', 'dang']
=> ["ding", "dong", "dang"]
irb(main):008:0> hello(arr1, arr2)
["baz", "stuff"]
[["ding", "dong", "dang"]]
=> nil
irb(main):009:0> hello(arr1, *arr2)
["baz", "stuff"]
["ding", "dong", "dang"]
=> nil

by adding the * to the second array, it treats them as an array instead of an array of an array, which is what you're looking for i think

Problem

I have a method that accepts the splat operator: ``` def hello(foo, *bar) #... do some stuff end ``` I have an array with a variable length that I'd like to send into this hello method: ``` arr1 = ['baz', 'stuff'] arr2 = ['ding', 'dong', 'dang'] ``` I'd like to call the method with arr1 and arr2 as arguments to that method but I keep getting hung up in that *bar is being interpreted as an array instead of individual arguments. To make things more fun, I can't change the hello method at all. I'm looking for something similar to this SO question but in ruby.

Original source

Related problems