Output a set of numbers (say, 1-15), but whenever a number is divisible by 3, you output “Fizz” instead. If it’s divisible by 5, you output “Buzz” instead. If it’s divisible by 3 and 5, you output “FizzBuzz” instead.
While it’s true that a rough-and-ready script-style version can be hacked together in a minute, it’s possible to learn a surprising amount of the Ruby language, best practices and toolsets merely by applying some creativity. Thus, “7 Degrees of FizzBuzz”.
To stretch your Ruby muscles, attempt the following seven challenges in the order they appear, building on your previous version with each new challenge. Useful resources are included to help you discover a number of the standard tools of the larger Ruby ecosystem.
Hopefully this adventure will expose you to a few new Ruby concepts (the more the better!), but if it’s all “old hat” to you, there are many benefits to treating it as a code kata: doing it from scratch regularly to improve efficiency and explore new options.
Have fun with it!
The “simplest thing that could possibly work”: i.e., a script. A typical implementation takes roughly a dozen lines. Hint: % is Ruby’s “modulo” operator… a % b divides a by b and returns the remainder. Resources: Ruby Docs, The Pickaxe Book
Wrap your script in a method that accepts an argument of how many numbers to output. The method will output the results itself.
Alter your method so that it collects the results and returns them to the caller. The caller will output the results.
Wrap your method in a class that also implements methods returning output as plain-text, JSON and HTML.
Test your class using the popular RSpec Test Framework. Does it:
- Return the correct response for the individual numbers 9, 10, 11 and 30?
- Does the class respond correctly when called with arguments of 15, 0, the string “fifteen” and nil (i.e.,
FizzBuzz.new("fifteen"))? - Do the 3 output methods return expected results?
Package your class as a simple, well-structured gem using Bundler and upload it to GitHub for sharing with other developers.
Use the Sinatra framework to make your gem accessible from any web browser, deploying your final version to Heroku. Try using Twitter Bootstrap to give it a bit of flair.
Extracted from Bill Gathen http://billgathen.com/2013/01/18/7_degrees_of_fizzbuzz.html