Day 10 of 30 Ruby Coding Challenge: Recursive Factorial Numbers

DZone 's Guide to

Day 10 of 30 Ruby Coding Challenge: Recursive Factorial Numbers

Day 10 of 30 - We are going solve the Factorial calculation using recursion in Ruby and learn a Ruby way to solve this type of problem.

· Web Dev Zone ·
Free Resource


Today, we’re going to solve the previous Factorial problem using recursion in Ruby. This is the written version of the Youtube video :).

Just a reminder, it doesn’t matter if you’re using Ruby, Python, JavaScript, or your favorite language — what really matters is the concepts and logic used to solve problems.

If you haven’t watched the previous video, I just want to remember the definition of a Factorial number

A Factorial number N is the product of all positive integers less than or equal to the number N

We indicate a Factorial number as N!

Real example:


A possible (and not so beautiful) solution to this problem is the solution in the first video:



Again, just recalling what recursion is:

Recursion is when you solve a problem by breaking the problem down into smaller versions of the same problem

And when it comes to coding, the method or function calls on itself :)

Before going to code, let’s see the first example:

Plain Text

But you can actually calculate this way:

Plain Text

Because 4! = 432*1, which is a small part of the 5! problem

You can go further and say:

Plain Text

A little bit more

Plain Text

And finally

Plain Text

Notice that we’ve broken that down into smaller Factorial calculations.

The recursive Ruby method will be like the following:


Notice that the function:

  • Returns 1 if the number is equal to 0. That’s the criteria to stop the method execution.
  • Returns number * factorial(number - 1) which, as we saw, is a method calling on itself.

A leaner version of this method in Ruby would be:


Also notice that:

  • We don’t need to explicitly use return in Ruby.
  • We’re using a ternary condition, which in our case makes the readability (in my opinion) much better.

That’s it!

Hope you liked it and see you tomorrow in the next challenge :).

Don’t forget to come by and say hi!

Twitter Youtube Instagram Linkedin GitHub

algorithm, algorithm analysis, coding, programming, programming language, rails, ruby, tutorial for beginners

Published at DZone with permission of Alexandre Gama . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}