Fizzbuzz with Ruby

What is Fizzbuzz?

  • A common interview question engineers see.
  • In this example we want to show a number divisible by 3, 5, or 3 and 5 returns a string.
    • 3 returns fizz.
    • 5 returns buzz.
    • 3 and 5 returns fizzbuzz.


def fizzbuzz(number)
  i = 1
  until i > number
    if i % 15  == 0
      puts "#{i} is divisible by 3 and 5 so return fizzbuzz"
    elsif i % 3  == 0
      puts "#{i} is only divisible by 3 so return fizz"
    elsif i % 5  == 0
      puts "#{i} is only divisible by 5 so return buzz"
  i += 1
  • Create a method that accepts an argument that will be a number.
  • Set a variable to 1 so as you iterate you have a starting point.
  • Setup an until loop where it will run until i is greater than the number given in the argument.
  • We then create an elsif statement where it will check if i is divisible by 15, 3, and 5.
    • Using if and elsif will only return the values that match.
    • We also place the check if something is divisible by 3 and 5 first because if we put it last one of the other conditions will be met first and would print out something we don’t expect.
  • Use % operator (Modulus) which divides the left side by the right side and returns the remainder. We then check if the answer is 0 to ensure we get only numbers that divide cleanly.
  • If the if or elsif condition is met print out the string.
  • Finally we want to continue to add to i until it reaches greater than the number argument so using += syntax tells ruby to add 1 to i.


288 Words

2019-01-02 17:40 +0000