Abid
Abid

Reputation: 7227

Ruby create a specific array from range

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

Answers (2)

tokland
tokland

Reputation: 67860

("00".."10").flat_map { |x| [x, x] }
#=> ["00", "00", "01", "01", ..., "10", "10"]

Upvotes: 7

clyfe
clyfe

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

Related Questions