0
\$\begingroup\$

I've implemented a factorial function in a more "Ruby" way. I would like to get feedback on the algorithm.

def factorial_of n
  (1..n).inject :*
end

factorial_of 5
=> 120
\$\endgroup\$
2
  • 1
    \$\begingroup\$ factorial_of 5 gives 15, not 120... Maybe you had another function and didn't paste in the correct one? \$\endgroup\$
    – Dair
    Commented Dec 11, 2018 at 0:35
  • \$\begingroup\$ So sorry! Just edited. I pasted it wrong. \$\endgroup\$
    – vinicius
    Commented Dec 11, 2018 at 0:36

1 Answer 1

4
\$\begingroup\$

The "of" in the name factorial_of is redundant and unconventional.

factorial_of 0 returns nil instead of the correct answer, which is 1.

def factorial(n)
  (1..n).inject(1, :*)
end
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.