Chris Ledet Chris Ledet - 7 months ago 36
Ruby Question

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?

Answer

You can do that with:

a.zip(s).flatten.compact