Skip to content

Instantly share code, notes, and snippets.

@djellemah
Last active May 24, 2016 07:09
Show Gist options
  • Save djellemah/9f77214c9d29a7cc931ef303db494d9f to your computer and use it in GitHub Desktop.
Save djellemah/9f77214c9d29a7cc931ef303db494d9f to your computer and use it in GitHub Desktop.
ruby pattern matching using refinements
class MatchIt
class Any
def ===( other ) true end
end
I = Any.new
module PatternMatch
refine Array do
def ===( other )
instances = Array other
each_with_index do |pattern,index|
pattern === instances[index] or return false
end
true
end
end
end
using PatternMatch
def match( arg1, arg2, arg3 )
case [arg1, arg2, arg3]
when [Enumerable, Enumerable] then :two_arrays
when [I,String] then :thing_and_string
when [Symbol, Symbol, Symbol] then :symbol_triple
else raise NotImplementedError, "No match for #{[arg1, arg2, arg3].inspect}"
end
end
end
# MatchIt.new.match :one, :two, :tre
# => :symbol_triple
# MatchIt.new.match [1,2,3], [4,5,6], :other_thing
# => :two_arrays
# MatchIt.new.match Object.new, "Woohoo", Math::PI
# => :thing_and_string
# MatchIt.new.match Object.new, :woohoo, Math::PI
# => NotImplementedError: No match for [#<Object:0xb250840>, :woohoo, 3.141592653589793]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment