Duplicate array elements in Ruby -


i have array rangers = ["red", "blue", "yellow", "pink", "black"] (it's debatable green should part of it, decided omitted it)

i want double array elements returns rangers = ["red", "red", "blue", "blue", "yellow", "yellow", "pink", "pink", "black", "black"] in order.

i tried around so, not find find way in order. (rangers *= 2 won't work).

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

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

how can duplicate elements return duplicate element value right next it? also, if possible, duplicate n times, when n = 3, returns ["red", "red", "red", "blue", "blue", "blue", ...]

how about

rangers.zip(rangers).flatten 

using array#zip , array#flatten?

a solution might generalize bit better second request might be:

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

using enumerable#flat_map. here can replace 2 value or variable.


Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -