module FizzBuzzExtension
refine Fixnum do
def fizz?
modulo(3).zero?
end
def buzz?
modulo(5).zero?
end
def fizz_buzz?
fizz? && buzz?
end
end
end
class FizzBuzz
using FizzBuzzExtension
def fizz_buzz(n)
1.upto(n).map{ |num| fizz_buzz_out(num) }
end
private
def fizz_buzz_out(n)
if n.fizz_buzz?
'FizzBuzz'
elsif n.fizz?
'Fizz'
elsif n.buzz?
'Buzz'
else
n
end
end
end
f = FizzBuzz.new
p result = f.fizz_buzz(10) # => [1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz"]
p result.join(', ') # => "1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz"
p 10.fizz? # => undefined method `fizz?' for 10:Fixnum (NoMethodError)