Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby create a specific array from range

Tags:

ruby

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

like image 470
Abid Avatar asked Jun 29 '12 12:06

Abid


People also ask

How do you create a range array in Ruby?

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.

How do you slice an array in Ruby?

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.

What does .first do in Ruby?

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.


2 Answers

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"]
like image 133
clyfe Avatar answered Oct 21 '22 06:10

clyfe


("00".."10").flat_map { |x| [x, x] }
#=> ["00", "00", "01", "01", ..., "10", "10"]
like image 22
tokland Avatar answered Oct 21 '22 07:10

tokland