Iterating Backwards Through A Ruby Array
This will be a quick one. I have seen alot of posts on StackOverflow about iterating backwards through a Ruby array. Ruby, in all its beauty, gives quite a few ways to iterate through an array.
Some of them are listed below:
disney = %w(Mickey Minnie Donald Goofy)
# using Array#each
disney.each { |val| puts val }
# using Enumerable#each_with_index
disney.each_with_index { |val, ind| puts "#{ind}: #{val}" }
# using Integer#times
disney.length.times { |ind| puts "#{ind}: #{disney[ind]}" }
These are just a few of the many ways. In other languages, iterating in the opposite direction can be kind of a pain in the…well you know. However, Ruby makes it a cinch. You can use the Array#reverse
method to reverse the order of the elements in the array before iterating over them.
disney = %w(Mickey Minnie Donald Goofy)
# using Array#each
disney.reverse.each { |val| puts val }
# using Enumerable#each_with_index
disney.reverse.each_with_index { |val, ind| puts "#{ind}: #{val}" }
Boom! Yeah, it’s that easy.