Skip to content

Instantly share code, notes, and snippets.

@fujimura
Created March 27, 2017 02:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fujimura/1787902f8ba908a466740326fb84b495 to your computer and use it in GitHub Desktop.
Save fujimura/1787902f8ba908a466740326fb84b495 to your computer and use it in GitHub Desktop.
module Match
def self.define_matchers!(m)
m.constants.each {|c|
eval "class #{c} < StandardError; end"
}
end
def self.match! obj
raise self.const_get(obj.class.to_s).new(obj)
end
end
Match.define_matchers! Object
def foo(arg)
Match.match! arg
rescue Match::String => s
p "this is a string"
p s
rescue Match::Fixnum => i
p "this is a Fixnum"
p i
end
foo 1
foo 'bar'
@fujimura
Copy link
Author

$ ruby p.rb
"this is a Fixnum"
#<Match::Fixnum: 1>
"this is a string"
#<Match::String: bar>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment