Created
January 30, 2014 14:16
-
-
Save regularfry/8709301 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 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