Some days ago I learnt about The FizzBuzz Test and did a simple implementation in Ruby. The FizzBuzz test is a simple algorithm that is supposed to do the following:

For each number from 1 to 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 3 and 5, print "FizzBuzz"
  • Otherwise print the number

I was just reading about how you can use the Enumerator class to have generators in the Programming Ruby 1.9 book, and thought that a good implementation could be done using just an Enumerator, so here it is, along with a simple RSpect test:

FizzBuzz = Enumerator.new do |yielder|
  count = 1
  loop do
    if count % 3 == 0
      if count % 5 == 0
        yielder.yield "FizzBuzz"
      else
        yielder.yield "Fizz"
      end
    elsif count % 5 == 0
      yielder.yield "Buzz"
    else 
      yielder.yield count
    end
    count += 1
  end
end

require_relative 'fizzbuzz'

describe FizzBuzz do
  before(:all) do
    @fizzbuzzes = FizzBuzz.first(100)
  end

  it "returns 'Fizz' for all multiples of 3" do
    @fizzbuzzes[3-1].should == 'Fizz'
  end

  it "returns 'Buzz' for all multiples of 5" do
    @fizzbuzzes[5-1].should == 'Buzz'

  end

  it "returns 'FizzBuzz' for all multiples of 3 and 5" do
    @fizzbuzzes[60 - 1].should == 'FizzBuzz'

  end

  it "returns the passed number if not a multiple of 3 or 5" do
    @fizzbuzzes[1 - 1].should == 1
  end
end

You can also find the code in its GitHub repository: https://github.com/brafales/ruby-fizzbuzz.