Day 7 of 30 - Ruby Coding Challenge - Factorial Numbers - Better Version

Day 7 of 30 - Ruby Coding Challenge - Factorial Numbers - Better Version

Hey folks!

In today’s post, which is the writing version of the Youtube video, we’ll rewrite the previous algorithm with a little bit better version. It’ll be really quick, I promise.

#1 - Algorithm Version 1. As usual, Ugly

Just to remember, this was the first algorithm version

def factorial(number)
  result = number
  while number > 1
    result = result * (number - 1)
    number = number - 1
  return result

puts factorial(1)

#2 - Algorithm Version 2. A Little Better

I’d like to keep the argument number intact, which means that I don’t want to use it to control my while loop

Ruby has an amazing and easy way to deal with arrays in this case

(1..(number - 1))

With the code above we’re saying to Ruby to iterate with numbers between 1 and number - 1.

Notice that number - 1 is the pattern used for each iteration.

(1..(number - 1)).each do |item|


Notice that the method each gives us the current number, which is the item, for each iteration

The final version would be:

def factorial_version_2(number)
  final_result = number
  (1..(number - 1)).each do |item|
    final_result = final_result * item
  return final_result

puts factorial_version_2(5)

As you can see, we avoid the number mutation, which means that our code is less error-prone and easier to read. Cool!

In the next video we’ll refactor this code a little bit more to reflect a more Ruby way to solve things. See you there :)

Don’t forget to keep in touch and say hi Alex

Twitter Youtube Instagram Linkedin GitHub

Join My Newsletter

You’ll receive coding courses, tutorials and personal posts! I’ll be happy to send them to you, weekly :)