2

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]
omikes
  • 8,064
  • 8
  • 37
  • 50
  • 2
    imo, `flat_map` is 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. – Cary Swoveland Mar 09 '17 at 06:04
  • `[i, 0]` expresses _"integers are each followed by a zero"_ pretty well. – Stefan Mar 09 '17 at 08:00

3 Answers3

5

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 }
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
3

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]
tadman
  • 208,517
  • 23
  • 234
  • 262
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 }
marmeladze
  • 6,468
  • 3
  • 24
  • 45