Monday, September 2, 2013

FizzBuzz in Ruby

FizzBuzz is a common and simple exercise in implementing the Strategy pattern. A brief synopsis of the Kata is as follows:

Print the numbers one through 100.
If the number is divisible by 3, print FIZZ.
If the number is divisible by 5, print BUZZ.
If the number is divisible by both, print FIZZBUZZ.
Using Ruby, the algorithm for this is quite straight forward using conditionals:
(1..100).each do |i|
  if i%3==0 and i%5==0
    puts "FIZZBUZZ"
  elsif i%3==0
    puts "FIZZ"
  elsif i%5==0
    puts "BUZZ"
  else
    puts i
  end
end

The kata only becomes interesting when you add an additional requirement; don't use conditionals. And of course, test drive your implementation. You can see my implementation on GitHub. I implemented two classes for processing a digit: Fizz and Buzz. These processors responded to process and processable? and were injected into a FizzBuzzRunner class along with the range. Additionally a default processor PassThrough was injected to the runner, which would be applied if no other processor was applicable and shared the same interface as the other processors.

The runner would query applicable_processors, asking each if the digit was processable?. If no processor was applicable, it would use the default, PassThrough. After collecting the applicable_processors, the results_from each processor were collected into an array. This allowed my final algorithm algorithm to read like well written prose.

class FizzBuzzRunner

  def initialize(range: range, processors: processors, default_processor: default_processor)
    @range = range
    @processors = processors
    @default_processor = default_processor
  end

  def as_string
    as_array.join(" ")
  end

  def as_array
    range.collect { |i| results_from(applicable_processors(i), i) }
  end
end

No comments:

Post a Comment