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
We use the double dot (..) and triple dot (…) to create a range in Ruby. The double dot notation produces a range of values, including the start and end values of the range. On the other hand, the three-dot notation will exclude the end (high) value from the list of values.
The array. slice() is a method in Ruby that is used to return a sub-array of an array. It does this either by giving the index of the element or by providing the index position and the range of elements to return.
Ruby | Array class first() function first() is a Array class method which returns the first element of the array or the first 'n' elements from the array.
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"]
("00".."10").flat_map { |x| [x, x] }
#=> ["00", "00", "01", "01", ..., "10", "10"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With