Search code examples
ruby-on-railsarraysrubyinterleave

Unequally interleave two ruby arrays


I'd like to interleave two arrays without exactly alternating them. For example, given:

a = [1,2,3,4,5,6,7,8,9]
b = ['a','b','c']

I'd like to receive f = [1,2,'a',3,4,'b',5,6,'c',7,8,9] as the output. I want one element from b for every two elements in a.

A solution appears to be:

a = [1,2,3,4,5,6,7,8,9]
b = ['a','b','c']

even, odd = a.partition.each_with_index{ |_, i| i.even? }
res = even.zip(odd,b)
res = res.flatten.reject(&:blank?)
#=> [1, 2, "a", 3, 4, "b", 5, 6, "c", 7, 8, 9]

but I'm not thrilled with this solution. Any ideas?


Solution

  • a.each_slice(2).zip(b).flatten
    #=> [1, 2, "a", 3, 4, "b", 5, 6, "c"]