Reverse an array without using a loop in ruby

后端 未结 8 515
时光说笑
时光说笑 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:08

    Konsolebox is right. If they are asking for the method without loops, that simply means that you cannot use any kind of loop whether it is map, each, while, until or any even built in methods that use loops, like length, size and count etc.

    Everything needs to be recursive:

    def recursive_reversal(array)
    
      return array if array == [] # or array.empty?
      last_element = array.pop
      return [last_element, recursive_reversal(array)].flatten
    
    end
    

    Ruby uses recursion to flatten, so flatten will not entail any kind of loop.

提交回复
热议问题