class Hash

Public Instance Methods

metch(search, default=nil) click to toggle source

Returns a value from the hash for the matching key

Similar to fetch, search the hash keys for the search string and return the corresponding value. Unlike fetch, however, if a hash key is a Regexp, the search string is matched against this Regexp. The hash is searched in it's natural order.

@example

h = { /aa/ => :aa, /a/ => :a, 'b' => :b }
h.metch('abc')          # => :a
h.metch('bcd')          # => KeyError
h.metch('b')            # => :b
h.metch('x', :foobar)   # => :foobar

@param search [String] string to search or matche against @param default [Object] fallback value if no key matched @return [Object] hash value @raise [KeyError] no key matched and no default given

   # File lib/core_ext/hash.rb
21 def metch(search, default=nil)
22   fetch search
23 rescue KeyError
24   each do |key, value|
25     next unless key.is_a? Regexp
26     return value if search.match? key
27   end
28   default ? default : raise(KeyError, "no match found: #{search.inspect}")
29 end