Fizz, buzz, fizzbuzz

Feb 06 2008

I was hit by a simple question today: write a fizzbuzz in ruby. Pretty fun anyway.

What’s Fizzbuzz?

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 started from this:

class Fixnum
...
end

I think it was a little overkill and slow the coding speed a lot. Here is the result:

def fizzbuzz
(1..100).each { |item|
puts print_value(item)
}
end

def print_value(item)
print_value = ''
print_value += 'Fizz' if item.div_by_3?
print_value += 'Buzz' if item.div_by_5?
print_value.empty? ? item : print_value
end

class Fixnum
def div_by_3?
self % 3 == 0
end

def div_by_5?
self % 5 == 0
end
end

fizzbuzz

Here are some simple samples from internet:
One liner:

1.upto(100) { |n| puts n % 3 == 0 ? n % 5 == 0 ? "fizzbuzz" : "buzz" : n % 5 == 0 ? "fizz" : n }

Another one liner:

puts (1..100).to_a.collect { |i| i % 15 == 0 ? ‘fizzbuzz’ : (i % 5 == 0 ? ‘fizz’ : (i % 3 == 0 ? ‘buzz’ : i)) }.join(’ ‘)

One more one liner

puts (1..100).map{|i|i%15==0?’FizzBuzz’:i%5==0?’Buzz’:i%3==0?’Fizz’:i}

Regular one, pretty close to mine:

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

Want to know more?

  1. Coding Horror:  Why Can’t Programmers.. Program?
  2. Imran On Tech: Using FizzBuzz to Find Developers who Grok Coding
  3. Wikipedia: Bizz buzz
  4. RubyQuiz: FizzBuzz (#126)

Go back to practice more, and more…

Tags:

2 responses so far

  1. [...] Since Libin points to “Fizz Buzz” in one line of Ruby, I feel it’s only fair to do it in one line of Python: [...]

  2. 1.upto(100){|n|puts”#{[:Fizz][n%3]}#{[:Buzz][n%5]}”[/.+/]||n}

Leave a Reply