File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

reverse traversing array in Ruby

 
Kavita Shivani
Ranch Hand
Posts: 45
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4121
IntelliJ IDE Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
Marc Peabody
pie sneak
Sheriff
Posts: 4727
Mac Ruby VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic