Iggy Iggy - 4 months ago 11
Ruby Question

Duplicate array elements in Ruby

I have an array

rangers = ["red", "blue", "yellow", "pink", "black"]
(it's debatable that green should part of it, but I decided to omitted it)

I want to double the array elements so it returns
rangers = ["red", "red", "blue", "blue", "yellow", "yellow", "pink", "pink", "black", "black"]
in that order.

I tried look around SO, but I could not find find a way to do it in that order. (
rangers *= 2
won't work).

I have also tried
rangers.map{|ar| ar * 2} #=> ["redred", "blueblue",...]


I tried
rangers << rangers #=> ["red", "blue", "yellow", "pink", "black", [...]]


How can I duplicate elements to return the duplicate element value right next to it? Also, if possible, I would like to duplicate it n times, so when
n = 3
, it returns
["red", "red", "red", "blue", "blue", "blue", ...]

Answer

How about

rangers.zip(rangers).flatten

using Array#zip and Array#flatten?

A solution that might generalize a bit better for your second request might be:

rangers.map { |ranger| [ranger] * 2 }.flatten

Here you can just replace the 2 with any value or variable. You could even shorten this to

rangers.flat_map { |ranger| [ranger] * n }

using Enumerable#flat_map.