Search code examples
arraysrubyinsertion

Insert value to every other array index in Ruby


I need to turn an array of integers like [1,2,3] into an array in which the integers are each followed by a zero: [1,0,2,0,3,0].

My best guess, which works but looks jenky:

> [1,2,3].flat_map{|i| [i,0]} => [1,0,2,0,3,0]

Solution

  • While Array#zip works pretty well, one might avoid the pre-creation of zeroes array by using Array#product:

    [1,2,3].product([0]).flatten
    

    or, just use a reducer:

    [1,2,3].each_with_object([]) { |e, acc| acc << e << 0 }