Reputation: 7227
I was wondering how can I generate the following array using ranges in ruby
["00","00","01","01","02", "02", ...... "10", "10"]
I want to repeat each element twice thats the part that I am looking an answer for. I can generate single elements as below
("00".."10").to_a
I know I can do this using loops etc but I am looking for a simpler one line code
Thanks
Upvotes: 6
Views: 4408
Reputation: 67860
("00".."10").flat_map { |x| [x, x] }
#=> ["00", "00", "01", "01", ..., "10", "10"]
Upvotes: 7
Reputation: 23770
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"]
Upvotes: 8