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]
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 }
Pretty straight forward with zip:
a = (1..10).to_a
b = Array.new(a.length, 0)
a.zip(b).flatten
# => [1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8, 0, 9, 0, 10, 0]
Array.new construct I always fear that I suddenly woke up in javascript land :) b = [0] * a.size?new Array() and that one is far more unpredictable as new Array(10) is an array of length 10, while new Array (10, 11) is a two element array. The Ruby one is more consistent: Array.new(size=0, default=nil)b = [0].cycleThis seems same as yours -))
[1,2,3].map {|i| [i, 0] }.flatten
Also this.
[1,2,3].collect {|x| [x, 0] }.flatten
Ugly and uneffective solution.
[1,2,3].join("0").split("").push(0).map{|s| s.to_i }
map in an alias for collect, that said first two are exactly same. The latter won’t work for 2-digits numbers.
flat_mapis ideal. It's efficient and reads well. Had you not mentioned it I would have given it as an answer. btw, your question is only implied. Best to always state the question.[i, 0]expresses "integers are each followed by a zero" pretty well.