Created
October 5, 2012 06:50
-
-
Save bmnick/3838448 to your computer and use it in GitHub Desktop.
Fizz Buzz (and possibly more) with a Chain of Responsibility
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
class Responder | |
def initialize(content, divisor, next_responder = FallbackResponder.new) | |
@content, @divisor, @next_responder = content, divisor, next_responder | |
end | |
def respond(value, current = '') | |
current << @content if value % @divisor == 0 | |
@next_responder.respond(value, current) | |
end | |
end | |
class FallbackResponder | |
def respond(value, current = '') | |
current == '' ? value : current | |
end | |
end | |
# Standard FizzBuzz | |
buzz = Responder.new("Buzz", 5) | |
fizz = Responder.new("Fizz", 3, buzz) | |
(1..100).each do |i| | |
puts fizz.respond(i) | |
end | |
# FizzBuzzBazz | |
bazz = Responder.new("Bazz", 7) | |
buzz = Responder.new("Buzz", 5, bazz) | |
fizz = Responder.new("Fizz", 3, buzz) | |
(1..100).each do |i| | |
puts fizz.respond(i) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment