Radek
Radek

Reputation: 11091

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

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]}

Upvotes: 50

Views: 43648

Answers (8)

Fadamiro Catherine
Fadamiro Catherine

Reputation: 1

We can also use "until":

index = array.length - 1
    
until index == -1
   p  arr[index]
   index -= 1
end

Upvotes: 0

Yaroslav  Yenkala
Yaroslav Yenkala

Reputation: 49

You can use "unshift" method to iterate and add items to new "reversed" array. Unshift will add a new item to the beginning of an array. While << - adding in the end of an array. Thats why unshift here is good.

array = [ 'first','middle','last']
output = []
                             # or: 
for item in array            #     array.each do |item|
  output.unshift(item)       #       output.unshift(item)            
end                          #     end

puts "Reversed array: #{output}"

will print: ["last", "middle", "first"]

Upvotes: 0

Mendy
Mendy

Reputation: 157

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"]
    

Upvotes: 4

divyum
divyum

Reputation: 1316

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

(0..5).reverse_each do |i|
  # do something
end

Upvotes: 9

lidox
lidox

Reputation: 1971

In a jade template you can use:

for item in array.reverse()
   item

Upvotes: 0

bakerstreet221b
bakerstreet221b

Reputation: 161

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

Upvotes: 3

allenwei
allenwei

Reputation: 4127

Ruby is smart

a = [ "a", "b", "c" ]
a.reverse_each {|x| print x, " " }

Upvotes: 110

ennuikiller
ennuikiller

Reputation: 46965

array.reverse.each { |x| puts x }

Upvotes: 60

Related Questions