Win a copy of Succeeding with AI this week in the Artificial Intelligence and Machine Learning forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
  • Junilu Lacar
Sheriffs:
  • Tim Cooke
  • Jeanne Boyarsky
  • Knute Snortum
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:
  • salvin francis
  • fred rosenberger
  • Frits Walraven

reverse traversing array in Ruby

 
Ranch Hand
Posts: 45
  • 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.
 
Bartender
Posts: 4121
IntelliJ IDE Spring Java
  • 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).
 
pie sneak
Posts: 4727
Mac VI Editor Ruby
  • 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.
 
Look! It's Leonardo da Vinci! And he brought a tiny ad!
Two software engineers solve most of the world's problems in one K&R sized book
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic