Skip to content

Instantly share code, notes, and snippets.

@crazymykl
Created November 20, 2013 18:49
Show Gist options
  • Save crazymykl/7568756 to your computer and use it in GitHub Desktop.
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.
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