Day 7 of 30 Ruby Coding Challenge: Factorial Numbers
Day 7 of 30. We're going to explore how to calculate Factorial Numbers in Ruby. This will be a better version that can be still improved later on.
Join the DZone community and get the full member experience.
Join For FreeHey folks!
In today’s post, which is the written 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.
xxxxxxxxxx
def factorial(number)
result = number
while number > 1
result = result * (number — 1)
number = number — 1
end
return result
end
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:
xxxxxxxxxx
(1..(number — 1))
With the code above, we’re saying to Ruby to iterate with numbers between 1 and number — 1.
Notice that -1 is the pattern used for each iteration.
xxxxxxxxxx
(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:
xxxxxxxxxx
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!
Published at DZone with permission of Alexandre Gama. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Reactive Programming
-
Building a Flask Web Application With Docker: A Step-by-Step Guide
-
5 Key Concepts for MQTT Broker in Sparkplug Specification
-
File Upload Security and Malware Protection
Comments