Last active
October 8, 2017 04:58
-
-
Save mtsmfm/f53a2f2f1722345b1eca80b3bda2160f to your computer and use it in GitHub Desktop.
FizzBuzz Quiz https://qiita.com/sumim/items/f26902f2b813c075a619
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class X < BasicObject | |
| MAP = { | |
| fizz: 3, | |
| buzz: 5 | |
| } | |
| def initialize(n) | |
| @n = n | |
| @result = nil | |
| end | |
| MAP.each do |name, x| | |
| define_method name do | |
| if @n.modulo(x).zero? | |
| @result ||= '' | |
| @result << name.to_s.capitalize | |
| end | |
| self | |
| end | |
| end | |
| private | |
| def method_missing(*args) | |
| result.__send__(*args) | |
| end | |
| def result | |
| @result || @n | |
| end | |
| end | |
| using Module.new { | |
| refine Integer do | |
| X::MAP.each_key do |k| | |
| define_method k do | |
| X.new(self).__send__(k) | |
| end | |
| end | |
| end | |
| } | |
| p 1.fizz #=> 1 | |
| p 3.fizz #=> "Fizz" | |
| p 1.buzz #=> 1 | |
| p 5.buzz #=> "Buzz" | |
| p 1.fizz.buzz #=> 1 | |
| p 3.fizz.buzz #=> "Fizz" | |
| p 5.fizz.buzz #=> "Buzz" | |
| p 15.fizz.buzz #=> "FizzBuzz" | |
| p 15.buzz.fizz #=> "BuzzFizz" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment