Hello,
Hello, I added FizzBuzz (1, 2, Fizz, 4, Buzz,...) by Example -
There's More Than One Way To Do It [1] by Tom Dalling, Paweł
Świątkowski, Gerald Bauer, et al to the Yuki & Moto Press Bookshelf
[2]
Free Online Books (and Booklets) about Ruby 'n' Friends in the
Manuscripts format and built with Jekyll and Octobook themes [3].
The FizzBuzz samples include Gold Standard, Classic, Monkey
Patching Fixnum, Object-Oriented w/ Fizznum, Enums, and many more.
I also included a RSpec Test Driven Development (TDD) sample - I'm
a RSpec newbie (and unbeliever ;-)) - if anyone can improve it or
show a better way - more than appreciated:-):
describe FizzBuzz do
describe "number is divisible" do
it "divisible by" do
divisible_by?(15,3).must_equal true
end
it "divisible by 3" do
divisible_by_3?(15).must_equal true
end
it "divisible by 5" do
divisible_by_5?(15).must_equal true
end
end
describe "number is fizzbuzz" do
before do
@result = fizzbuzz
end
it "returns 'Fizz' for multiples of 3" do
@result[3-1].must_equal "Fizz"
end
it "returns 'Buzz' for multiples of 5" do
@result[5-1].must_equal "Buzz"
end
it "returns 'FizzBuzz' for multiples of 3 and 5" do
@result[15-1].must_equal "FizzBuzz"
end
it "returns the passed number if not a multiple of 3 or 5" do
@result[1-1].must_equal 1
end
end
end
And here's another fizzbuzz algorithm with a classic for loop and
using divisible_by? and case/when/else clauses:
def divisible_by?(numerator, denominator)
numerator % denominator == 0
end
def divisible_by_3?( numerator )
divisible_by?( numerator, 3 )
end
def divisible_by_5?( numerator )
divisible_by?( numerator, 5 )
end
def fizzbuzz
result = []
for n in 1..100 do
result << case
when divisible_by_3?(n) && divisible_by_5?(n) then "FizzBuzz"
when divisible_by_3?(n) then "Fizz"
when divisible_by_5?(n) then "Buzz"
else n
end
end
result
end
Happy reading. Happy coding. Happy fizzbuzzing. Cheers.
[1] http://yukimotopress.github.io/fizzbuzz
[2] http://yukimotopress.github.io
[3] https://github.com/octobook