Reverse an array without using a loop in ruby

后端 未结 8 456
时光说笑
时光说笑 2021-01-24 12:12

I have a coding challenge to reverse a an array with 5 elements in it. How would I do this without using the reverse method?

Code:

def reverse(array)
 a         


        
8条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-24 13:01

    You can treat array as a stack and pop the elements from the end:

    def reverse(array)
      rev = []
      rev << array.pop until array.empty?
      rev
    end
    

    or if you don't like modifying objects, use more functional-like reduce:

    def reverse(array)
      array.reduce([]) {|acc, x| [x] + acc}
    end
    

    Cary mentioned in the comment about the performance. The functional approach might not be the fastest way, so if you really want to do it fast, create a buffor array and just add the items from the end to begin:

    def reverse(array)
      reversed = Array.new(array.count)
      array.each_with_index do |item, index|
        reversed[-(index + 1)] = item
      end
      reversed
    end
    

提交回复
热议问题