From: Josh Cheek Date: 2010-01-04T01:46:48+09:00 Subject: Re: Few clarifications on recursion --000e0cd1b0aebdb293047c455971 Content-Type: text/plain; charset=ISO-8859-1 > > Although it introduces many interesting concepts to me (i. e. I did not > knew that after the "if" statement a single _1_ with no quotes could be > used) I fail to see how the num changes value. The way I read the code here: > > In Ruby, the last line of a function is returned. In this case, the last line is the if statement. The if statement evaluates to the last line of code inside of it. This means that if the number is less than or equal to 1, the last line of the if statement will be 1, so that is what the if statement will evaluate to, and thus that is what the function will return. > num * factorial(num-1) > > is 30*29 for "puts factorial(30)" not 30*29*28... which is how it works. > I've tested the code works fine. > > This is the recursive portion, it is not 30*29, it is 30*factorial(29), and factorial(29) is 29*factorial(28) and factorial(28) is 28*factorial(27) etcetera until you get to 1, and factorial(1) is just 1, because it is less than or equal to 1. If you expand these calls out, you get 30*( 28*( 27*( ... *(1) ) ) ) If you are still confused by this, try going the other way. Start with 1, and go up. If factorial(1) returns 1, what will factorial(2) return (go through the code)? And then what will factorial(3) return? And so on. --000e0cd1b0aebdb293047c455971--