Ruby creates a specific array from a range

I was wondering how can I generate the next array using ranges in ruby

["00","00","01","01","02", "02", ...... "10", "10"] 

I want to repeat each element twice, the part I'm looking for an answer to. I can create individual elements below

 ("00".."10").to_a 

I know I can do this with loops, etc., but I'm looking for simpler, single line code

thanks

+6
source share
2 answers
 ("00".."10").flat_map { |x| [x, x] } #=> ["00", "00", "01", "01", ..., "10", "10"] 
+6
source

Use Array # zip and Array # flatten :

 a = ("00".."10").to_a a.zip(a).flatten # ["00", "00", "01", "01", "02", "02", "03", "03", "04", "04", "05", "05", "06", "06", "07", "07", "08", "08", "09", "09", "10", "10"] 
+8
source

Source: https://habr.com/ru/post/919323/


All Articles