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

后端 未结 6 1965
别那么骄傲
别那么骄傲 2020-12-30 19:08

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

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

index = array.length
array.length.t         


        
6条回答
  •  再見小時候
    2020-12-30 19:37

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

提交回复
热议问题