Ruby: recursive method

前端 未结 3 922
半阙折子戏
半阙折子戏 2021-01-17 06:32
def reverse_append(arr, n)  
    return arr if n < 0 
    reverse_append(arr, n-1)
    arr << n
    arr
end 

reverse_append([],4) #=> [0, 1, 2, 3, 4]
         


        
3条回答
  •  半阙折子戏
    2021-01-17 06:58

    There's a nice tool you can add to many editors called "Seeing Is Believing", which lets you see what is happening as code runs:

    def reverse_append(arr, n)  
      return arr if n < 0 # => false, false, false, false, true
      reverse_append(arr, n-1) # => [], [0], [0, 1], [0, 1, 2]
      arr << n # => [0], [0, 1], [0, 1, 2], [0, 1, 2, 3]
      arr # => [0], [0, 1], [0, 1, 2], [0, 1, 2, 3]
    end 
    
    reverse_append([], 3) # => [0, 1, 2, 3]
    

    However, with a name like "reverse_append" it seems like you should see a result that is descending in values:

    def reverse_append(arr, n)  
      return arr if n < 0 # => false, false, false, false, true
      reverse_append(arr, n-1) # => [], [0], [1, 0], [2, 1, 0]
      arr.unshift n # => [0], [1, 0], [2, 1, 0], [3, 2, 1, 0]
      arr # => [0], [1, 0], [2, 1, 0], [3, 2, 1, 0]
    end 
    
    reverse_append([], 3) # => [3, 2, 1, 0]
    

    In either case, there are a lot of easier ways to generate such an array without relying on recursion:

    [*0..3] # => [0, 1, 2, 3]
    (0..3).to_a # => [0, 1, 2, 3]
    
    [*0..3].reverse # => [3, 2, 1, 0]
    (0..3).to_a.reverse # => [3, 2, 1, 0]
    

提交回复
热议问题