Skip to content

Instantly share code, notes, and snippets.

@philcallister
Created June 25, 2014 18:09
Show Gist options
  • Save philcallister/a30f182418d4541c5e68 to your computer and use it in GitHub Desktop.
Save philcallister/a30f182418d4541c5e68 to your computer and use it in GitHub Desktop.
A little too much fun with FizzBuzz
module FunFizzBuzz
class ModResult
include Comparable
attr_accessor :mod, :result_proc
def initialize(mod, result_proc)
self.mod = mod
self.result_proc = result_proc
end
def <=> other
self.mod <=> other.mod
end
end
class Sequencer
attr_accessor :max
def initialize(max)
self.max = max
end
def sequence(mod_procs)
mps = mod_procs.sort.reverse # need to test biggest divisors first
(1..self.max).each do |i|
mp_found = mps.detect { |mp| i % mp.mod == 0 }
puts mp_found ? mp_found.result_proc.call(i) : block_given? ? yield(i) : i
end
end
end
end
s = FunFizzBuzz::Sequencer.new(100)
mps = [FunFizzBuzz::ModResult.new(3, Proc.new { |i| "Fizz" }), FunFizzBuzz::ModResult.new(5, Proc.new { |i| "Buzz" }), FunFizzBuzz::ModResult.new(15, Proc.new { |i| "FizzBuzz" })]
s.sequence(mps)
mps = [FunFizzBuzz::ModResult.new(2, Proc.new { |i| "FizzNew #{i}" }), FunFizzBuzz::ModResult.new(3, Proc.new { |i| "BuzzNew #{i}" }), FunFizzBuzz::ModResult.new(6, Proc.new { |i| "FizzBuzzNew #{i}" })]
s.sequence(mps)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment