Getting down range sequence in Ruby

So it works in ascending order

(1..5).to_a => [1, 2, 3, 4, 5] 

But it is not

 (5..1).to_a => [] 

I am trying to get a downward sequence from an arbitrary ceiling. Thanks.

+4
source share
2 answers

Try the following:

 5.downto(1).to_a # => [5, 4, 3, 2, 1] 

Of course there is a corresponding #upto . If you need steps, you can do this:

 1.step(10, 2).to_a # => [1, 3, 5, 7, 9] 10.step(1, -2).to_a # => [10, 8, 6, 4, 2] 
+14
source

Or you can try the following: (1..5).to_a.reverse # => [5, 4, 3, 2, 1]

+5
source

All Articles