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]
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]
This 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 }