Skip to content

Instantly share code, notes, and snippets.

@regularfry
Created January 30, 2014 14:16
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 regularfry/8709301 to your computer and use it in GitHub Desktop.
Save regularfry/8709301 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
class Matcher
def initialize( *args, &blk )
@args = args
@blk = blk
end
def call( *params )
matches = @args.zip(params).all?{|arg, param|
arg.nil? || arg === param
}
@blk.call if matches
end
end
module Kernel
def pattern( *args, &blk )
$MATCHERS=[]
yield
$MATCHERS.each do |matcher|
result = matcher.call( *args )
return result if result
end
end
def match( *args, &blk )
$MATCHERS << Matcher.new( *args, &blk )
end
def _; nil; end
end
(1..100).each do |i|
puts pattern(i%3, i%5) {
match(0,0){ "FizzBuzz" }
match(0,_){ "Fizz" }
match(_,0){ "Buzz" }
match(_){ i }
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment