Guest User

Untitled

a guest
Sep 23rd, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. # FizzBuzz module iterates over a sequence of numbers, printing
  2. # 'Fizz' on multiples of three, 'Buzz' for multiples of five,
  3. # 'FizzBuzz' on multiples of both three and five, and otherwise
  4. # prints the number itself.
  5. module FizzBuzz
  6. # Main class that runs the application.
  7. class App
  8. # Constructor, checks and stores options.
  9. #
  10. # *Params*
  11. # +options+: Hash containing :to and :from parameters.
  12. def initialize(options)
  13. # Make sure to/from values are provided as integers.
  14. unless options.has_key?(:from) && options[:from] % 1 === 0 &&
  15. options.has_key?(:to) && options[:to] % 1 === 0
  16. raise ArgumentError, 'Please provide to and from options as whole numbers.'
  17. end
  18.  
  19. @from = options[:from].to_i
  20. @to = options[:to].to_i
  21. end
  22.  
  23. # Run application and print output based on parameters passed
  24. # to constructor.
  25. def run
  26. # Iterate over provided numbers.
  27. @from.upto @to do |number|
  28. if number.is_fizzbuzz
  29. puts 'FizzBuzz'
  30. elsif number.is_fizz
  31. puts 'Fizz'
  32. elsif number.is_buzz
  33. puts 'Buzz'
  34. else
  35. puts number
  36. end
  37. end
  38. end
  39. end
  40.  
  41. # Utility methods to be included in Kernel::Integer.
  42. module Integer
  43. # True if integer is multiple of three.
  44. def is_fizz
  45. self % 3 === 0
  46. end
  47.  
  48. # True if integer is multiple of five.
  49. def is_buzz
  50. self % 5 === 0
  51. end
  52.  
  53. # True if integer is multiple of three and five.
  54. def is_fizzbuzz
  55. is_fizz && is_buzz
  56. end
  57. end
  58. end
  59.  
  60. Integer.send :include, FizzBuzz::Integer
  61.  
  62. app = FizzBuzz::App.new from: 1, to: 100
  63. app.run
Add Comment
Please, Sign In to add comment