Skip to content

Instantly share code, notes, and snippets.

/defmulti ? Secret

Created July 19, 2011 00:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/d78805b13870b6570a9c to your computer and use it in GitHub Desktop.
Save anonymous/d78805b13870b6570a9c to your computer and use it in GitHub Desktop.
#!/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