6

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

2 Answers 2

8

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"]
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.