Skip to content

Instantly share code, notes, and snippets.

@gregawoods
Created February 24, 2013 18:10
Show Gist options
  • Save gregawoods/5024874 to your computer and use it in GitHub Desktop.
Save gregawoods/5024874 to your computer and use it in GitHub Desktop.
Applying the experimental Ruby 2.0 Refinements feature to the classic FizzBuzz challenge. (http://www.codinghorror.com/blog/2007/02/why-cant-programmers-program.html)
module FizzBuzz
refine Fixnum do
def to_s
if self % 3 == 0 && self % 5 == 0
"FizzBuzz"
elsif self % 3 == 0
"Fizz"
elsif self % 5 == 0
"Buzz"
else
super
end
end
end
end
(1..20).collect{ |n| n.to_s }.join(', ')
# => "1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20"
using FizzBuzz
(1..20).collect{ |n| n.to_s }.join(', ')
# => "1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16, 17, Fizz, 19, Buzz"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment