Search code examples
rubyrecursionfactorial

Understanding, Recursion in Ruby


In recursion, a method calls itself. I'm not following it when there are return values. For example, in the "Learn to Program" book by Chris Pine, there is this example on factorials.

def factorial num 
  if num < 0
    return 'You cant\'t take the factorial of a negative number!'
  end
  if num <= 1
    1
  else 
    num * factorial(num-1)
  end
end 

If I call the method factorial(3), it will go to the else portion of the code and will look like this:

3 * factorial(3-1)

and should return 6 since 3*2=6. factorial(3-1) calls the factorial method passing 2 within the recursion. num = 2, and thus 2 * factorial(2-1) and 2*1=2.

What happens to the 6 that we got from our first run through the code? Now that num = 1, it looks like this will now return 1 and go to the end of the code. But from my understanding, we still have 6 and 2 from the previous recursions. Am I correct in this assumption, since we called the factorial function when we multiplied by num? Can someone help me understand this better? Say we called factorial(10), how would this work out?


Solution

  • First, you should replace your return 'blabla' with a raise 'blabla' because your function returns a numeric, not a string.

    Then see it like this

    factorial(3)
      3 * factorial(2)
            2 * factorial(1)
                  1  # no more recursion, let's go up replacing 
                     # the function calls by the returned value
                end
          end
    end
    # ↓
    factorial(3)
      3 * factorial(2)
            2 * 1  # let's go up again !
          end
    end
    # ↓
    factorial(3)
      3 * 2 # finally
    end
    # ↓
    6