Day 9 of 30 Ruby Coding Challenge: Factorial Numbers - Final Functional Version

DZone 's Guide to

Day 9 of 30 Ruby Coding Challenge: Factorial Numbers - Final Functional Version

Day 8 of 30 - Ruby Coding Challenges in 30 Days. We're going to explore how to calculate Factorial Numbers in Ruby using a more declarative approach, which is a concept borrowed from functional programming cs

· Web Dev Zone ·
Free Resource

Hey folks!

In today’s post, which is the written version of the Youtube video, we’ll finally finish in an elegant way our journey of writing Factorials in Ruby.

#1 - Algorithm Version 3. Ruby Rocks

This is the previous solution to our problem if calculating Factorial in Ruby


#2 - Algorithm Version 4. It Can Be Even Better

Now, it’s to know the method downto(), which can be called with numbers!

We can just ask Ruby, "Can you iterate from a number down to another number?"

Take a look at this code:


Notice that the result will be numbers between 10 and 1, which Ruby handles automatically. Nice!

The next (and final) step just indicates to Ruby that we want a reduced value from this list of numbers.

We can easily do that using the method reduce() that we met in the previous algorithm

The final result:



If you want to compare with the first version:


One final note: I completely forgot to validate the Factorial of zero, which is by definition 1.

I don’t want to add complexity, so I’ll just add a conditional in the method:


There we go. Much simpler, which means, more readable, and maintainable

Thanks for the visit and see you in the next challenge :)

Don’t forget to come by and say hi!

Twitter Youtube Instagram Linkedin GitHub

algorithm, algorithm analysis, coding, coding bootcamp, 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 }}