Merge and interleave two arrays in Ruby

I have the following code:

a = ["Cat", "Dog", "Mouse"]
s = ["and", "&"]

I want to merge the array s into array a which would give me:

["Cat", "and", "Dog", "&", "Mouse"]

Looking through the Ruby Array and Enumerable docs, I don't see such a method that will accomplish this.

Is there a way I can do this without iterating through each array?


You can do that with:

a.zip(s).flatten.compact

This won't give a result array in the order Chris asked for, but if the order of the resulting array doesn't matter, you can just use a |= b. If you don't want to mutate a, you can write a | b and assign the result to a variable.

See the set union documentation for the Array class at http://www.ruby-doc.org/core/classes/Array.html#M000275.

This answer assumes that you don't want duplicate array elements. If you want to allow duplicate elements in your final array, a += b should do the trick. Again, if you don't want to mutate a, use a + b and assign the result to a variable.

In response to some of the comments on this page, these two solutions will work with arrays of any size.


If you don't want duplicate, why not just use the union operator :

new_array = a | s