Ruby

Day 8 of 30 - Ruby Coding Challenge - Factorial Numbers - Functional Version 1

Day 8 of 30 - Ruby Coding Challenge - Factorial Numbers - Functional Version 1

Hey folks!

In today’s post, which is the writing version of the Youtube video, we’ll finally achieve our dreams of writing the Factorial Algorithm in a more Ruby way. This will be very short because, well, that’s the way Ruby solves things 😄

#1 - Previous Algorithm Version

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)

It’s easy to understand, however, it could be simpler

#2 - Ruby Way for Factorial Numbers

Ruby allows us to reduce a list of arrays into a single value by applying a method, which in our case will be the multiplier method

def factorial_version_3(number)
  (1..number).reduce(:*)
end

puts factorial_version_3(5)

What’s happening is:

  • ruby iterates over the numbers, between 1 and the given number
  • then Ruby reduces this list of numbers into a single value by applying the given method, which multiplies the numbers

Pretty straightforward and cool, isn’t it?

In the next video we’ll explore the final version of this algorithm, which can be frighteningly easier. 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 :)