| Author |
reverse traversing array in Ruby
|
Kavita Shivani
Ranch Hand
Joined: Aug 14, 2009
Posts: 45
|
|
Hi everyone,
I am trying to traverse in reverse order using for loop in ruby. But the following code does not print anything. Please can anyone tell me if there is anything wrong in the code.
thanks,
Kavitha.
|
 |
Nathan Pruett
Bartender
Joined: Oct 18, 2000
Posts: 4121
|
|
The problem is that the range (10 ... 5) isn't doing what you think it is - it's *not* giving you a reverse range (i.e. - How many numbers are between 10 and 5?), it's giving you an empty range (i.e. How many numbers are between 10 and 5 that are greater than 10 and less than 5?).
You can use (4..10).to_a.reverse, or (10.downto(4)).to_a to get the range of values you're expecting. (I'm assuming that you meant to use the '...' exclusive range rather than the '..' inclusive range, so the last value should be 4.) These options produce an Array instead of a Range, but they work the same in the for loop (or with each() or many of the other ways to iterate in Ruby).
|
-Nate
Write once, run anywhere, because there's nowhere to hide! - /. A.C.
|
 |
Marc Peabody
pie sneak
Sheriff
Joined: Feb 05, 2003
Posts: 4725
|
|
|
Also of note: Rubyists rarely, if ever, use a for loop. The more common idiom is to call each or one of the other iterator-based methods directly on the array.
|
A good workman is known by his tools.
|
 |
 |
|
|
subject: reverse traversing array in Ruby
|
|
|