From: Victor Reyes Date: 2008-07-14T21:53:53+09:00 Subject: Re: Factorials ------=_Part_67558_30223868.1216040302946 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline On Sun, Jul 13, 2008 at 8:04 PM, Serabe wrote: > The easy way: > > def factorial(n) > if n==1 > 1 > else > n*factorial(n-1) > end > end > > puts factorial(5) > > It prints 120. > > A more ruby way method: > > def factorial(n) > (1..n).inject(1) {|product, n| product * n } > end > > puts factorial(5) > > It does also print 120. > > Regards, > > Serabe > > -- > http://www.serabe.com > > The "Rubish" version of your factorial solutions appear to be much faster! Although I find it more confusing than the "traditional" recursive solution. I guess my problem is understanding the role of the *inject* method. I use 100 instead of 5 to make it run a bit longer. def factorial(n) if n==1 1 else n*factorial(n-1) end end puts factorial(100) timex ruby factorial01 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 real 0.05 user 0.00 sys 0.00 ==================================================== def factorial(n) (1..n).inject(1) {|product, n| product * n } end puts factorial(100) timex ruby factorial02 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 real 0.02 user 0.00 sys 0.00 Regards, Victor ------=_Part_67558_30223868.1216040302946--