Skip to content

Instantly share code, notes, and snippets.

@haileys
Created September 6, 2013 18:24
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save haileys/6467886 to your computer and use it in GitHub Desktop.
Save haileys/6467886 to your computer and use it in GitHub Desktop.
class Module
def dispatch(*klasses, last)
last_klass, mid = last.first
klasses << last_klass
__dispatch_list << [klasses, instance_method(mid)]
define_method(mid, __dispatch_proc(__dispatch_list))
end
def __dispatch_list
@__dispatch_list ||= []
end
def __dispatch_proc(dispatch_list)
proc { |*args, &bk|
_, meth = dispatch_list.find { |klasses, meth|
args.size == klasses.size && args.zip(klasses).all? { |arg, klass| klass === arg }
}
raise TypeError, "bad argument types in method call" unless meth
meth.bind(self).call(*args, &bk)
}
end
end
class Foo
dispatch String, String => def bar(a, b)
a + b
end
dispatch Integer, Integer => def bar(a, b)
a * b
end
end
puts Foo.new.bar("hello ", "world")
puts Foo.new.bar(9, 9)
@makefunstuff
Copy link

Could you explain why am I getting TypeError but method definition works fine?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment