File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Ruby and the fly likes reverse traversing array in Ruby Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Languages » Ruby
Bookmark "reverse traversing array in Ruby" Watch "reverse traversing array in Ruby" New topic

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.

Nathan Pruett

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).

Write once, run anywhere, because there's nowhere to hide! - /. A.C.
Marc Peabody
pie sneak

Joined: Feb 05, 2003
Posts: 4727

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.
I agree. Here's the link:
subject: reverse traversing array in Ruby
It's not a secret anymore!