Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a descending range sequence in Ruby

Tags:

range

ruby

So this works ascendingly

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

But this doesn't

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

I'm trying to get a descending sequence from an arbitrary ceiling. Thanks.

like image 614
steve_gallagher Avatar asked Jun 19 '12 14:06

steve_gallagher


2 Answers

Try this:

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

Of course, there's a corresponding #upto. If you want 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]
like image 64
Sergio Tulentsev Avatar answered Dec 15 '22 11:12

Sergio Tulentsev


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

like image 43
Tomasz Weissbek Avatar answered Dec 15 '22 09:12

Tomasz Weissbek