Skip to content

Instantly share code, notes, and snippets.

@bkerley
Created December 27, 2011 21:34
Show Gist options
  • Save bkerley/1525230 to your computer and use it in GitHub Desktop.
Save bkerley/1525230 to your computer and use it in GitHub Desktop.
require 'pp'
class PatternObject
def initialize
@patterns = Hash.new
end
def method_missing(name, *args)
candidates = @patterns[name]
winner = candidates.detect do |c|
c.match args
end
raise 'aaaaaa' unless winner
winner.invoke args
end
def pattern(function_name, *options, &block)
@patterns[function_name] ||= []
@patterns[function_name] << Pattern.new(options, block)
end
end
class Pattern
def initialize(options, block)
@options = options
@block = block
end
def invoke(args)
@block.call *args
end
def match(args)
@options.zip args do |o, a|
return false unless o === a
end
return true
end
end
zzz = PatternObject.new
zzz.pattern :asdf, Fixnum, /bra+ins/ do
puts "i'ma zombie arrrrr"
end
zzz.pattern :asdf, Fixnum, String do
puts 'called with fixnum and string'
end
zzz.pattern :asdf, Fixnum, Fixnum do
puts 'called with two fixnums'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment