Module: Algebrick::Matching
Overview
include this module anywhere yoy need to use pattern matching
Instance Method Summary collapse
- #any ⇒ Object
- #match(value, *cases) ⇒ Object
- #match?(value, *cases) ⇒ Boolean
- #on(matcher, value = nil, &block) ⇒ Object
Instance Method Details
#any ⇒ Object
18 19 20 |
# File 'lib/algebrick/matching.rb', line 18 def any Matchers::Any.new end |
#match(value, *cases) ⇒ Object
22 23 24 25 26 |
# File 'lib/algebrick/matching.rb', line 22 def match(value, *cases) success, result = match? value, *cases raise "no match for (#{value.class}) '#{value}' by any of #{cases.map(&:first).join ', '}" unless success result end |
#match?(value, *cases) ⇒ Boolean
28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/algebrick/matching.rb', line 28 def match?(value, *cases) cases = if cases.size == 1 && cases.first.is_a?(Hash) cases.first else cases end cases.each do |matcher, block| return true, Matching.match_value(matcher, block) if matcher === value end [false, nil] end |
#on(matcher, value = nil, &block) ⇒ Object
41 42 43 44 45 46 47 48 49 |
# File 'lib/algebrick/matching.rb', line 41 def on(matcher, value = nil, &block) matcher = if matcher.is_a? Matchers::Abstract matcher else matcher.to_m end raise ArgumentError, 'only one of block or value can be supplied' if block && value [matcher, value || block] end |