brycemcd
brycemcd

Reputation: 4513

Sending elements of an array as arguments to a method call

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.

Upvotes: 15

Views: 10334

Answers (2)

mportiz08
mportiz08

Reputation: 10318

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

Upvotes: 15

Jacob Relkin
Jacob Relkin

Reputation: 163248

Here you go:

hello('Something', *(arr1 + arr2))

This will combine the arr1 and arr2 arrays and collectively pass them from the second argument on to the method.

Example:

>> def hello(str, *args)
>> puts str
>> args.each do |arg|
?>   puts 'Splat: ' + arg
>> end
>> end
=> nil
>> hello('Hello', *(['programming'] + ['is', 'fun']))
Hello
Splat: programming
Splat: is
Splat: fun
=> ["programming", "is", "fun"]

The last parameter of a method may be preceded by an asterisk(*), this indicates that more parameters may be passed to the function. Those parameters are collected up and an array is created.

Since the last parameters are collected up into an array, you need to use the * operator to indicate that you are indeed sending an array to the method and that it shouldn't wrap the arguments in another array.

Upvotes: 10

Related Questions