Created
April 19, 2012 18:38
-
-
Save Veejay/2422901 to your computer and use it in GitHub Desktop.
Dumb and basic version of pattern matching construct in Ruby
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
class Array | |
def extract_options! | |
last.is_a?(::Hash) ? pop : {} | |
end | |
end | |
def match(*args) | |
rules = args.extract_options! | |
if rules.has_key?(*args) | |
rules[*args].call | |
else | |
rules[:default].call(*args) | |
end | |
end | |
def fibonacci x | |
match x, | |
0 => ->{0}, | |
1 => ->{1}, | |
:default => ->(n){fibonacci(n-1) + fibonacci(n-2)} | |
end | |
puts fibonacci(20) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment