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.
Just to remember, this was the first algorithm version
def factorial(number) result = number while number > 1 result = result * (number - 1) number = number - 1 end return result end puts factorial(1)
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| end
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 end return final_result end 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
You’ll receive coding courses, tutorials and personal posts! I’ll be happy to send them to you, weekly :)