Reverse an array without using a loop in ruby

后端 未结 8 457
时光说笑
时光说笑 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 12:50

    Here's another non-destructive approach:

    arr = ["a", 1, "apple", 8, 90]
    
    arr.size.times.with_object([]) { |_,a| a << arr.rotate!(-1).first }
      #=> [90, 8, "apple", 1, "a"]
    arr
      #=> ["a", 1, "apple", 8, 90] 
    

    Another would the most uninteresting method imaginable:

    (arr.size-1).downto(0).with_object([]) { |i,a| a << arr[i] }
      #=> [90, 8, "apple", 1, "a"]
    arr
      #=> ["a", 1, "apple", 8, 90]    
    

提交回复
热议问题