Sunday, August 2, 2009

Interleave two arrays

Assuming the arrays are of equal length this code interleaves the two arrays to create a new array.
a1 = %w(1 2 3 4)
a2 = %w(a b c d)

a3 = (0..a1.length - 1).map {|i| [a1[i], a2[i]]}.flatten
#=> ["1", "a", "2", "b", "3", "c", "4", "d"]

# or
a3 = (0..a1.length - 1).inject([]) {|n, i| n << a1[i] << a2[i]}
#=> ["1", "a", "2", "b", "3", "c", "4", "d"]

# or
a1.each_with_index {|x,i| a2.insert(i*2, a1[i])}
#=> ["1", "a", "2", "b", "3", "c", "4", "d"]

# or
[a1, a2].transpose.flatten
#=> ["1", "a", "2", "b", "3", "c", "4", "d"]

# or
a1.zip(a2).flatten
#=> ["1", "a", "2", "b", "3", "c", "4", "d"]

http://snippets.dzone.com/posts/show/7652

No comments: