?> How to make FizzBuzz test with Ruby – Camel Dev

How to make FizzBuzz test with Ruby

FizzBuzz test was one of the simplest test in logical test. Especially for new developer, this test often given. Basic logic of this is test looping. So, if you understand about limited loop this test look easy for you. In other C like programming language usually using for to pass this algorithm. But in this article I will use Ruby to solve this test.

Main flow of this test are :

  1. Doing loop from 1 to 100 and print every number one by one
  2. If number could be divided by 3, replace it with “Fizz”
  3. Do the same like item 2 but for number divided by 3 and replace it with “Buzz” text
  4. If number could be divided by 3 and 5. You can simply it with divided by 15 too. Replace number with “FizzBuzz”

I have created several alternative to pass FizzBuzz test :

Using Each loop

(1..100).each do |x|
 if x % 3 == 0 && x % 5 == 0
   puts "FizzBuzz"
 elsif x % 3 == 0 
   puts "Fizz"
 elsif x % 5 == 0
   puts "Buzz"
 else
   puts x
 end
end

Using Upto loop

1.upto(100) do |x|
 if x % 15 == 0
   puts "FizzBuzz"
 elsif x % 3 == 0 
   puts "Fizz"
 elsif x % 5 == 0
   puts "Buzz"
 else
   puts x
 end
end

Using Times loop

100.times do |x|
 x += 1
 if x % 3 == 0 && x % 5 == 0
   puts "FizzBuzz"
 elsif x % 3 == 0 
   puts "Fizz"
 elsif x % 5 == 0
   puts "Buzz"
 else
   puts x
 end
end

All above script will get the same result. Loop from 1 to 100, replacing number which could divided by 3 with “Fizz” string text,  doing the same for number divided 5 but replacing it with “Fizz” string text. Additional term is number could divided by 5 and 3 replaced by “FizzBuzz” string text.

But I little bit difficult to print screen result. So, I try to modify one of those script.

Modification flow

puts "FizzBuzz by CamelDev.Com"
text = "Line 1 ~> "
1.upto(100) do |x|
 if x % 15 == 0
   text += "FizzBuzz"
 elsif x % 3 == 0 
   text += "Fizz"
 elsif x % 5 == 0
   text += "Buzz"
 else
   text += x.to_s
 end
 
 if x % 10 == 0 && x != 100
   line = (x/10) + 1
   text += "\nLine #{line} ~> "
 elsif x != 100
   text += " - "
 end
end

puts text

No matter what style used result will be the same. The most important thing you understand about basic flow of this test, Looping in certain number. Hopefully its useful.

Add a Comment

Your email address will not be published. Required fields are marked *