Skip to content

Instantly share code, notes, and snippets.

@bmnick
Created October 5, 2012 06:50
Show Gist options
  • Save bmnick/3838448 to your computer and use it in GitHub Desktop.
Save bmnick/3838448 to your computer and use it in GitHub Desktop.
Fizz Buzz (and possibly more) with a Chain of Responsibility
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