Skip to content

Instantly share code, notes, and snippets.

@Veejay
Created April 19, 2012 18:38
Show Gist options
  • Save Veejay/2422901 to your computer and use it in GitHub Desktop.
Save Veejay/2422901 to your computer and use it in GitHub Desktop.
Dumb and basic version of pattern matching construct in Ruby
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