Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 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
Add Comment
Please, Sign In to add comment