-
-
Save anonymous/d78805b13870b6570a9c to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env ruby | |
class GenericFunction | |
def initialize | |
@dispatchers = {} | |
end | |
def add_dispatcher match, action | |
@dispatchers[match] = action | |
end | |
def dispatch *args | |
@dispatchers.each do |match,action| | |
action.call *args if match.call *args | |
end | |
end | |
end | |
gf = GenericFunction.new | |
gf.add_dispatcher( | |
Proc.new {|a,b| a.respond_to? :quack and b.respond_to? :listen }, | |
Proc.new {|a,b| b.listen a.quack } | |
) | |
class Animal; def listen message; puts "I heard #{message}"; end; end | |
class Duck < Animal; def quack; "quack"; end; end | |
gf.dispatch Duck.new, Animal.new |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment