Merge and interleave two arrays in Ruby
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.
You can do that with:
a.zip(s).flatten.compact
s.inject(a, :<<)
s #=> ["and", "&"]
a #=> ["Cat", "Dog", "Mouse", "and", "&"]
It doesn't give you the order you asked for, but it's a nice way of merging two arrays by appending to the one.
If you don't want duplicate, why not just use the union operator :
new_array = a | s