Created
September 30, 2013 05:07
-
-
Save alg/6759578 to your computer and use it in GitHub Desktop.
Ruby Multi-dispatch
This file contains 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
module Kernel | |
MDEF_DEFINED = {} | |
def mdef(name, *types, &block) | |
sig = gen_sig(name, types) | |
MDEF_DEFINED[name] = (MDEF_DEFINED[name] || []) + [ sig ] | |
Kernel.send(:define_method, sig, &block) | |
end | |
def gen_sig(name, types) | |
[ name, types.map(&:to_s).join("_") ].compact.join("_") | |
end | |
def method_missing(name, *args) | |
if defs = MDEF_DEFINED[name] | |
sig = gen_sig(name, args.map { |a| a.class }) | |
return send(sig, *args) if defs.include?(sig) | |
end | |
super(name, *args) | |
end | |
end | |
mdef(:met, Fixnum) do |arg| | |
arg + arg | |
end | |
mdef(:met, String) do |str| | |
str.upcase | |
end | |
puts met(1) # 1 + 1 = 2 | |
puts met("a") # a -> A |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment