Created
March 17, 2012 12:38
-
-
Save hawx/2058456 to your computer and use it in GitHub Desktop.
Define a instance method with a class method crazy-meta-ness
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 Base | |
def self.method_missing(sym, *args, &block) | |
send :define_method, sym, (args.empty? ? block : args[0].to_proc) | |
end | |
end | |
class A < Base | |
intify :to_i | |
floatify :to_f | |
end | |
class B < Base | |
die {|n| 'DIE!' * n } | |
end | |
a = A.new | |
p a.intify '123' | |
#=> 123 | |
p a.floatify '123' | |
#=> 123.0 | |
b = B.new | |
p b.die 5 | |
#=> 'DIE!DIE!DIE!DIE!DIE!' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment