Skip to content

Instantly share code, notes, and snippets.

@adambird
Created March 18, 2013 20:30
Show Gist options
  • Save adambird/5190532 to your computer and use it in GitHub Desktop.
Save adambird/5190532 to your computer and use it in GitHub Desktop.
After hearing today that we using Fizz Buzz in our dev interview process I thought I'd better have a go. Here's my attempt at finding the first 100 Fizz Buzz numbers with tests. So should I get through this stage?
class FizzBuzzNumber
def initialize(value)
@value = value
end
def to_s
out = []
out << "fizz" if @value % 3 == 0
out << "buzz" if @value % 5 == 0
out.length > 0 ? out.join(" ") : @value.to_s
end
def fizz_or_buzz?
to_s != @value.to_s
end
end
class TestSuite
def run
STDOUT.sync = true
errors = []
to_s_cases = [
[1, "1"],
[2, "2"],
[3, "fizz"],
[4, "4"],
[5, "buzz"],
[6, "fizz"],
[10, "buzz"],
[15, "fizz buzz"],
]
fizz_or_buzz_cases = [
[1, false],
[2, false],
[3, true],
[4, false],
[5, true],
[5, true],
[10, true],
[15, true]
]
run_tests :to_s, to_s_cases, errors
run_tests :fizz_or_buzz?, fizz_or_buzz_cases, errors
puts ""
puts errors.length > 0 ? "#{errors.length} failures" : "Success"
errors.each do |e| puts e end
end
def run_tests(method, cases, errors)
cases.each do |inputs|
begin
run_test method, inputs[0], inputs[1]
print "."
rescue => e
errors << e.message
print "F"
end
end
end
def run_test(method, number, expected)
actual = FizzBuzzNumber.new(number).send(method)
unless actual == expected
raise StandardError.new("#{method} for #{number} is #{actual} not #{expected}")
end
end
end
TestSuite.new.run
max_items = 100
fizzbuzz_count = 0
counter = 1
output = []
while fizzbuzz_count < max_items do
number = FizzBuzzNumber.new(counter)
fizzbuzz_count += 1 if number.fizz_or_buzz?
output << number
counter += 1
end
puts output.join(", ")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment