1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
101.times do |n| next if n == 0 case true when (n%5) == 0 && (n%3) == 0 puts "fizzbuzz" when ((n%3) == 0) puts "fizz" when (n%5) == 0 puts "buzz" else puts n end end
Refactorings
No refactoring yet !
Matt
January 15, 2010, January 15, 2010 15:48, permalink
Here's my crack at it...
1 2 3 4 5 6 7 8 9 10
101.times do |n| next if n == 0 result = '' result += (n%3 == 0) ? 'fizz' : '' result += (n%5 == 0) ? 'buzz' : '' result += (result.length < 1) ? "#{n}" : '' puts result end
Pavel Gorbokon
January 15, 2010, January 15, 2010 17:48, permalink
1 2 3 4 5 6 7
1.upto(100) do |n| s = "" s << "fizz" if n%3 == 0 s << "buzz" if n%5 == 0 s = "#{n}" if s.empty? puts s end
Pavel Gorbokon
January 15, 2010, January 15, 2010 18:16, permalink
1 2 3 4 5 6
def fizzbuzz(n) s = [[5, "fizz"],[3, "buzz"]].select{|(div, msg)| n%div == 0 }.map{|(div, msg)| msg }.join s.empty? ? n.to_s : s end puts (1..100).map {|n| fizzbuzz(n) }
Martin Plöger
January 16, 2010, January 16, 2010 12:35, permalink
1 2 3 4 5 6 7 8
def fizzbuzz max (1..max).map do |n| s = ['fizz'][n%3].to_s + ['buzz'][n%5].to_s s.empty? ? n.to_s : s end end puts fizzbuzz(100)
Matt
January 16, 2010, January 16, 2010 15:58, permalink
2nd stab
1 2 3 4
1.upto(100) do |n| print (n%3 == 0) ? 'fizz' : '' puts (n%5 == 0) ? 'buzz' : (n%3 == 0) ? '' : n end
Matt
January 16, 2010, January 16, 2010 16:37, permalink
1 2 3 4
1.upto(100) do |n| s = "#{n%3 == 0 ? 'fizz' : ''}#{n%5 == 0 ? 'buzz' : ''}" puts s.empty? ? n : s end
Martin Plöger
January 18, 2010, January 18, 2010 20:40, permalink
1
puts (1..100).map { |n| ['fizzbuzz'][n%3+n%5] || ['fizz'][n%3] || ['buzz'][n%5] || n }
Martin Plöger
January 18, 2010, January 18, 2010 21:13, permalink
You could also use 15 as the Least common multiple of 3 and 5:
1
puts (1..100).map { |n| [:fizzbuzz][n%15] || [:fizz][n%3] || [:buzz][n%5] || n }
Enonatan
February 15, 2010, February 15, 2010 23:21, permalink
So, if we are looking for the shortest solution... I need a way to make empty string nil, but the only idea is regexp (
1
puts (1..50).map { |n| "#{[:fizz][n%3]}#{[:buzz][n%5]}"[/.+/] || n }
Wrote a Fizz Buzz http://en.wikipedia.org/wiki/Bizz_buzz#Other_uses solution in Ruby. It works but I'm sure it could be better/more concise.