Created
April 5, 2012 04:44
-
-
Save dnordstrom/2308000 to your computer and use it in GitHub Desktop.
FizzBuzzer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1.upto(100) do |nr| | |
if nr % 3 === 0 && nr % 5 === 0 | |
puts 'FizzBuzz' | |
elsif nr % 3 === 0 | |
puts 'Fizz' | |
elsif nr % 5 === 0 | |
puts 'Buzz' | |
else | |
puts nr | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# FizzBuzz module iterates over a sequence of numbers, printing | |
# 'Fizz' on multiples of three, 'Buzz' for multiples of five, | |
# 'FizzBuzz' on multiples of both three and five, and otherwise | |
# prints the number itself. | |
module FizzBuzz | |
# Main class that runs the application. | |
class App | |
# Constructor, checks and stores options. | |
# | |
# *Params* | |
# +options+: Hash containing :to and :from parameters. | |
def initialize(options) | |
# Make sure to/from values are provided as integers. | |
unless options.has_key?(:from) && options[:from] % 1 === 0 && | |
options.has_key?(:to) && options[:to] % 1 === 0 | |
raise ArgumentError, 'Please provide to and from options as whole numbers.' | |
end | |
@from = options[:from].to_i | |
@to = options[:to].to_i | |
end | |
# Run application and print output based on parameters passed | |
# to constructor. | |
def run | |
# Iterate over provided numbers. | |
@from.upto @to do |number| | |
if number.is_fizzbuzz | |
puts 'FizzBuzz' | |
elsif number.is_fizz | |
puts 'Fizz' | |
elsif number.is_buzz | |
puts 'Buzz' | |
else | |
puts number | |
end | |
end | |
end | |
end | |
# Utility methods to be included in Kernel::Integer. | |
module Integer | |
# True if integer is multiple of three. | |
def is_fizz | |
self % 3 === 0 | |
end | |
# True if integer is multiple of five. | |
def is_buzz | |
self % 5 === 0 | |
end | |
# True if integer is multiple of three and five. | |
def is_fizzbuzz | |
is_fizz && is_buzz | |
end | |
end | |
end | |
Integer.send :include, FizzBuzz::Integer | |
app = FizzBuzz::App.new from: 1, to: 100 | |
app.run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment