Skip to content

Instantly share code, notes, and snippets.

@mtsmfm
Last active October 8, 2017 04:58
Show Gist options
  • Select an option

  • Save mtsmfm/f53a2f2f1722345b1eca80b3bda2160f to your computer and use it in GitHub Desktop.

Select an option

Save mtsmfm/f53a2f2f1722345b1eca80b3bda2160f to your computer and use it in GitHub Desktop.
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