Henry Verissimo
3 min readMay 21, 2021

--

FizzBuzz is a classic task, usually used in software development interviews to determine if a candidate can code if you're new to programming. Here’s the classic FizzBuzz task:

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

Since we just need to loop through each number from 1 to 100, one of the simplest FizzBuzz solutions can be done with a for loop:

def fizz_buzz
(1..20).each do |n|
if (n % 3 == 0) puts "Fizz"
elsif (n % 5 == 0) puts "Buzz"
elsif (i % 5 == 0) puts "FizzBuzz"
else puts n
end
end
end
fizzbuzz

Awesome! If you run this code in your console, you’ll see this works just fine. Here’s a snippet of the loop:

There are probably hundreds of different ways to solve FizzBuzz. Some are cleaner, faster, and better than others. Some are just plain.

def fizz_buzz(n)end

So we have a method fizz_buzz which has an argument of (n). The first thing we need to do is iterate over the collection of numbers. We will use the inclusive range operator, which we will then each over.

def fizz_buzz(n)         (1..n).each do |num|

end
end

After that, we will create an if statement. This is where we will start testing out numbers. We have to test for multiples three and five first. Otherwise, we won’t make it because three and five separately would fulfill that requirement. The modulo operator divides the left number by the right number and returns a remainder. We know that if no remainder exists then the number is multiple.

def fizz_buzz(n)    

(1..n).each do |num|
if num % 3 == 0 && num % 5 == 0
"FizzBuzz"
end
end

For the next to requirements we basically just split the first one and change the return. To finish the if statement we just return the number if it doesn’t meet any of the requirements. Some test sites like Leetcode to Hankerrank might want you to convert the number to a string. In this case, just attached “.to_s” to num.

def fizz_buzz(n)     (1..n).each do |num|
if num % 3 == 0 && num % 5 == 0
"FizzBuzz"
elsif num % 3 == 0
"Fizz"
elsif num % 5 == 0
"Buzz"
else
num
end
end
end

That’s it, a simple way to solve a fairly simple problem. The problem I had originally is not fully understanding the modulo operator. Once I figured out how that worked, it made it easy to figure out the rest.

CONCLUSION

FizzBuzz is one of those common problems that is deeply ingrained in programming culture with memes abound. It’s a fun problem that can be daunting in the beginning, but once you master it you can move on to more difficult problems. Hopefully, this was helpful. Let me know if you can think of a DRYer way to write the method.

--

--