|
| 1 | +# lookup.rb -- simple keyword lookup routine |
| 2 | +# |
| 3 | +# Alan K. Stebbens <[email protected]> |
| 4 | +# |
| 5 | +# require 'lookup' |
| 6 | +# |
| 7 | +# lookup - lookup a keyword in a list, in a case-insensitive, disambiguous way |
| 8 | +# |
| 9 | +# :call-seq: |
| 10 | +# result = lookup list, key, err_notfound="%s not found", err_ambig="% is ambiguous" |
| 11 | +# result = list.lookup( key, err_notfound, err_ambig ) |
| 12 | +# result = list.lookup( key, err_notfound ) |
| 13 | +# result = list.lookup( key ) |
| 14 | +# |
| 15 | +# Lookup key in list, which can be an array or a hash. Return the one that |
| 16 | +# matches exactly, or matches using case-insensitive, unambiguous matches, or |
| 17 | +# raise a LookupError with a message. |
| 18 | +# |
| 19 | +# LookupError is a subclass of StandardError. |
| 20 | +# |
| 21 | +# LookupNotFoundError, a subclass of LookupError, is raised when a keyword is |
| 22 | +# not found, and only if `err_notfound` is not nil. |
| 23 | +# |
| 24 | +# LookupAmbigError, a subsclass of LookupError, is raised when a keyword search |
| 25 | +# matches multiple entries from the list, and only if `err_ambig` is not nil. |
| 26 | +# |
| 27 | +# If err_notfound is nil, do not raise a LookupNotFoundError error, and return |
| 28 | +# nil. |
| 29 | +# |
| 30 | +# If err_ambigmsg is nil, do not raise a LookupAmbigError, and return the list |
| 31 | +# of possible results. |
| 32 | + |
| 33 | +class LookupError < StandardError ; end |
| 34 | +class LookupNotFoundError < LookupError ; end |
| 35 | +class LookupAmbigError < LookupError ; end |
| 36 | + |
| 37 | +def key_lookup list, key, err_notfound="%s not found\n", err_ambig="%s is ambiguous\n" |
| 38 | + keylist = list.is_a?(Hash) ? list.keys : list |
| 39 | + if exact = keylist.grep(/^#{key}$/i) # exact match? |
| 40 | + return exact.shift if exact && exact.size == 1 |
| 41 | + end |
| 42 | + keys = keylist.grep(/^#{key}/i) |
| 43 | + case keys.size |
| 44 | + when 0 |
| 45 | + unless err_notfound.nil? |
| 46 | + raise LookupNotFoundError, sprintf(err_notfound, key) |
| 47 | + end |
| 48 | + return nil |
| 49 | + when 1 |
| 50 | + return keys[0] |
| 51 | + else |
| 52 | + unless err_ambig.nil? |
| 53 | + raise LookupAmbigError, sprintf(err_ambig, key) |
| 54 | + end |
| 55 | + return keys |
| 56 | + end |
| 57 | +end |
| 58 | + |
| 59 | +alias lookup key_lookup |
| 60 | + |
| 61 | +class Array |
| 62 | + def lookup key, err_notfound="%s not found\n", err_ambig="%s is ambiguous\n" |
| 63 | + key_lookup self, key, err_notfound, err_ambig |
| 64 | + end |
| 65 | +end |
| 66 | + |
| 67 | +class Hash |
| 68 | + def lookup key, err_notfound="%s not found\n", err_ambig="%s is ambiguous\n" |
| 69 | + self.keys.lookup(key, err_notfound, err_ambig) |
| 70 | + end |
| 71 | +end |
0 commit comments