Juan Artau
Juan Artau

Reputation: 357

Combine two arrays in specific order

I need to combine these two arrays:

A = ["Dog", "Cat", "Bird"]
B = ["John", "Doe", "Foo"]

I must take the first element of the first array and then the first element of the second array, then the second element of the first array and the second element of the second array and so on. It has to be in this exact order:

["Dog", "John", "Cat", "Doe", "Bird", "Foo"]

Upvotes: 1

Views: 67

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110675

Array.new(2*A.size) { |i| i.even? ? A[i/2] : B[i/2] }
  #=> ["Dog", "John", "Cat", "Doe", "Bird", "Foo"]

Upvotes: 0

falsetru
falsetru

Reputation: 368954

You can use Array#zip to get [[A[0], B[0]], [A[1], B[1]], ...]

A.zip(B)
# => [["Dog", "John"], ["Cat", "Doe"], ["Bird", "Foo"]]

Flattening it will give you what you want:

A.zip(B).flatten
# => ["Dog", "John", "Cat", "Doe", "Bird", "Foo"]

UPDATE alternative using Enumerable#flat_map:

(0...A.size).map { |i| [A[i], B[i]] }
# => [["Dog", "John"], ["Cat", "Doe"], ["Bird", "Foo"]]
(0...A.size).flat_map { |i| [A[i], B[i]] }
# => ["Dog", "John", "Cat", "Doe", "Bird", "Foo"]

Upvotes: 7

Related Questions