Skip to content

Instantly share code, notes, and snippets.

@k-tsj
Created May 20, 2019 13:55
Show Gist options
  • Save k-tsj/ab1622266547d83c57caf28736490c59 to your computer and use it in GitHub Desktop.
Save k-tsj/ab1622266547d83c57caf28736490c59 to your computer and use it in GitHub Desktop.
module Extractor
MATCH_FAILED = []
def MATCH_FAILED.length
-1
end
def ===(obj)
unapply = method(:unapply)
obj.singleton_class.define_method(:deconstruct) do
singleton_class.remove_method(:deconstruct)
unapply.call(obj)
end
true
end
end
class EMail
class << self
prepend Extractor
def unapply(obj)
parts = obj.to_s.split(/@/)
if parts.length == 2
parts
else
Extractor::MATCH_FAILED
end
end
end
end
case 'foo-bar@example.com'
in EMail(name, domain)
p name #=> "foo-bar"
p domain #=> "example.com"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment