Created
July 26, 2012 12:23
-
-
Save owainlewis/3181737 to your computer and use it in GitHub Desktop.
Pattern Matching DSL
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
# Pattern matching DSL ideas | |
class Object | |
def method_missing method_name, *args, &block | |
if method_name.to_s == "_" | |
:default | |
else | |
super | |
end | |
end | |
end | |
module PatternMatch | |
def self.match x, &block | |
h = block.call() | |
match = h[x] | |
match.nil? ? h[:default] : match | |
end | |
end | |
def matcher n | |
result = PatternMatch::match n do { | |
10 => "It is 10", | |
20 => "It is 20", | |
_ => "No match" } | |
end | |
end | |
puts matcher(10) | |
puts matcher(200) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment