fork download
  1. def def_fizzBuzz(sel, n)
  2. Integer.class_eval{
  3. define_method(sel){
  4. (m = self) % n == 0 ?
  5. sel.to_s.capitalize.instance_eval{ @x = m; self} :
  6. self
  7. }
  8. }
  9. String.class_eval{
  10. define_method(sel){
  11. (m = self.instance_eval{ @x }) % n == 0 ?
  12. (self+sel.to_s.capitalize).instance_eval{ @x = m; self} :
  13. self
  14. }
  15. }
  16. end
  17.  
  18. def_fizzBuzz :fizz, 3
  19. def_fizzBuzz :buzz, 5
  20. def_fizzBuzz :gizz, 7
  21.  
  22. p 1.fizz.buzz #=> 1
  23. p 3.fizz.buzz #=> "Fizz"
  24. p 5.fizz.buzz #=> "Buzz"
  25. p 15.fizz.buzz #=> "FizzBuzz"
  26. p 7.fizz.buzz.gizz #=> "Gizz"
  27. p 21.fizz.buzz.gizz #=> "FizzGizz"
  28. p 35.fizz.buzz.gizz #=> "BuzzGizz"
  29. p 105.fizz.buzz.gizz #=> "FizzBuzzGizz"
  30. p 105.fizz.gizz.buzz #=> "FizzGizzBuzz"
  31. p 999.fizz.buzz #=> "Fizz"
  32.  
  33. p 1.fizz.buzz + 2 #=> 3
  34. p (1.fizz.buzz + 2.buzz).fizz #=> "Fizz"
  35. p 15.fizz.buzz.gizz + "XXX" #=> "FizzBuzzXXX"
Success #stdin #stdout 0.02s 7436KB
stdin
Standard input is empty
stdout
1
"Fizz"
"Buzz"
"FizzBuzz"
"Gizz"
"FizzGizz"
"BuzzGizz"
"FizzBuzzGizz"
"FizzGizzBuzz"
"Fizz"
3
"Fizz"
"FizzBuzzXXX"