Last Updated: February 25, 2016
·
1.411K
· irichlau

FizzBuzz question

One of the most common fizz buzz question is this one:

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

I wrote this in ruby.
At first my goal was just to get it to work and this is what I got.

range = 1..100
range.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

This worked and my next step was to refactor it. I used what I learned recently in the Ruby course in Codecademy and this is what I came up with.

(1..100).each{ |x|
y = ""
y += '"Fizz" if x % 3 == 0
y += ''Buzz" if x % 5 == 0
puts ( y.empty? ? x : y )
}

When x is a multiple of 3 it will add the word "fizz" to y
when x is a multiple of 5 it will add the word "buzz" to y
when its a multiple of both it will add both the word fizz and buzz to y.
I used the ternary operator to show the number if it isn't fizz, buzz or fizzbuzz.
That last line basically says if y is empty then it's true and x will be displayed. If it's not empty (fizzbuzz inside) then it's false and y will be displayed.

puts (y.empty? ? true : false);

Hope it helps someone

2 Responses
Add your response

I don't think the refactor helps, since it makes your code less legible than before!
Of course it's full of idioms, and some sugar but the first one is pretty readable. If you want to show your language expertise, you may use the refactored version. If not asked, I'd prefer the first one.

over 1 year ago ·

When I answered this question I wrote the answer using the zero? method instead.

(1..100).each do |i|
  if (i%3).zero? && (i%5).zero?
    puts "FizzBuzz"
  elsif (i%3).zero?
    puts "Fizz"
  elsif (i%5).zero?
    puts "Buzz"
  else
    puts i
  end
end
over 1 year ago ·