Alex Rivera | Logout

Merge and interleave two arrays in Ruby

Asked 2011-09-05T21:02:33.527
110

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?

Edit
Report

1 Answer

174

You can do that with:

a.zip(s).flatten.compact
answered 2011-09-05T21:15:54.303

Your Answer