Created
November 20, 2013 18:49
-
-
Save crazymykl/7568756 to your computer and use it in GitHub Desktop.
Implement a generalized FizzBuzz, FooBaz, such that FooBaz((1..100), {3 => "Fizz", 5 => "Buzz"}) is equivalent to FizzBuzz.
This file contains 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 FooBaz | |
attr_reader :replacements, :range | |
def initialize range, replacements | |
@range = range | |
@replacements = replacements | |
end | |
def call | |
range.each do |number| | |
puts substitute number | |
end | |
end | |
private | |
def substitute n | |
replacement = replacement_for n | |
replacement.empty? ? n : replacement | |
end | |
def replacement_for n | |
replacements.map { |divisor, replacement| | |
replacement if (n % divisor).zero? | |
}.join | |
end | |
end | |
def FooBaz range=(1..100), replacements={3 => "Fizz", 5 => "Buzz"} | |
FooBaz.new(range, replacements).() | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment