Hubert Jakubiak Hubert Jakubiak - 2 months ago 26
Ruby Question

How to map array [1,2,3] to [1,1,2,2,3,3] in Ruby?

I'm looking for the quickest way to map array:

[1,2,3]


to

[1,1,2,2,3,3]


I ended up with something like below. But it's not what I need.

[1,2,3].map { |n| [n,n] } => [[1, 1], [2, 2], [3, 3]]

Answer

You can try flat_map

arr.flat_map{ |n| [n,n] }
#=> [1, 1, 2, 2, 3, 3]