How to iterate through an array starting from the last element? (Ruby)

0 votes
asked Feb 27, 2010 by radek

I came with below solution but I believe that must be nicer one out there ...

array = [ 'first','middle','last']

index = array.length
array.length.times { index -= 1; puts array[index]}

6 Answers

0 votes
answered Jan 27, 2010 by allenwei

Ruby is smart

a = [ "a", "b", "c" ]
a.reverse_each {|x| print x, " " }
0 votes
answered Feb 27, 2010 by ennuikiller
array.reverse.each { |x| puts x }
0 votes
answered Jan 10, 2013 by bakerstreet221b

You can even use a for loop

array = [ 'first','middle','last']
for each in array.reverse do
   print array
end

will print

last
middle
first
0 votes
answered Jan 14, 2015 by lidox

In a jade template you can use:

for item in array.reverse()
   item
0 votes
answered Jan 20, 2016 by divyum

In case you want to iterate through a range in reverse then use:

(0..5).reverse_each do |i|
  # do something
end
0 votes
answered Sep 15, 2017 by mendy

If you want to achieve the same without using reverse [Sometimes this question comes in interviews]. We need to use basic logic.

  1. array can be accessed through index
  2. set the index to length of array and then decrements by 1 until index reaches 0
  3. output to screen or a new array or use the loop to perform any logic.

        def reverseArray(input)
          output = []
          index = input.length - 1 #since 0 based index and iterating from 
          last to first
    
          loop do
            output << input[index]
            index -= 1
            break if index < 0
          end
    
          output
        end
    
        array = ["first","middle","last"]
    
        reverseArray array #outputs: ["last","middle","first"]
    
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...