My first thought:
(1..100).each do |i|
case
when i % 15 == 0
puts "FizzBuzz"
when i % 3 == 0
puts "Fizz"
when i % 5 == 0
puts "Buzz"
else
puts i
end
end
If I took 30 seconds to think about it on an interview, I would have a
unit test (see my earlier post) and something like this:
module Enumerable
def map_every(n)
m = n - 1
result = []
self.each_with_index do |elem,i|
if i % n == m
result << yield(elem,i)
else
result << elem
end
end
result
end
end
result = *1..100
result = result.map_every(3) { "Fizz" }
result = result.map_every(5) { "Buzz" }
result = result.map_every(15) { "FizzBuzz" }
puts result
----------------------------------------
I peeked on the mailing list, so I won't participate in the golf
tournament -- and I am not particularly good at golfing in any case.
pth