Iggy
Iggy

Reputation: 5251

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", ...]

Upvotes: 5

Views: 5339

Answers (1)

Julian Kniephoff
Julian Kniephoff

Reputation: 1023

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.flat_map { |ranger| [ranger] * 2 }

using Enumerable#flat_map. Here you can just replace the 2 with any value or variable.

Upvotes: 9

Related Questions