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
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Dec 11, 2018 at 0:27
\$\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\$ Commented Dec 11, 2018 at 0:35
  • \$\begingroup\$ So sorry! Just edited. I pasted it wrong. \$\endgroup\$ 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
answered Dec 11, 2018 at 1:26
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.