{{announcement.body}}
{{announcement.title}}

Day 7 of 30 Ruby Coding Challenge: Factorial Numbers

DZone 's Guide to

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.

· Web Dev Zone ·
Free Resource

Hey 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.

Ruby
 




xxxxxxxxxx
1
10


 
1
def factorial(number)
2
  result = number
3
  while number > 1
4
    result = result * (number1)
5
    number = number1
6
  end
7
  return result
8
end
9
 
          
10
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:

Ruby
 




xxxxxxxxxx
1


 
1
(1..(number1))



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.

Ruby
 




xxxxxxxxxx
1


 
1
(1..(number1)).each do |item|
2
 
          
3
end



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

The final version would be:

Ruby
 




xxxxxxxxxx
1


 
1
def factorial_version_2(number)
2
  final_result = number
3
  (1..(number1)).each do |item|
4
    final_result = final_result * item
5
  end
6
  return final_result
7
end
8
9
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!

Twitter Youtube Instagram Linkedin GitHub

Topics:
algorithm, algorithm analysis, code, coding, programming, programming language, rails, ruby, tutorial, 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 }}