A
Adam Trager
I just started using ruby, and no matter how hard i try i cant do
factorials. how to a get the factorial of an imported number?
factorials. how to a get the factorial of an imported number?
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
Victor said:I guess my problem is understanding the role of the *inject* method.
Same problem here. But I figured out it's ideal for calculating
summations and products, where you'd use a big Sigma or Pi in
mathematics.
Surprisingly Fortran never had Sigma or Pi constructs; we had to roll
our own using a DO loop. Same for subsequent languages. Ruby is the
first language I've come across with it built in.
Maybe someone would explain why it's called "inject" though?
2008/7/14 Victor Reyes said: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.
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.