Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/core_ext/hash.rb

Direct Known Subclasses

AIPP::THash

Instance Method Summary collapse

Instance Method Details

#metch(search, default = :__n_o_n_e__) ⇒ Object

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 argument is matched against this Regexp. The hash is searched in its natural order.

Examples:

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

Parameters:

  • search (String)

    string to search or matche against

  • default (Object) (defaults to: :__n_o_n_e__)

    fallback value if no key matched

Returns:

  • (Object)

    hash value

Raises:

  • (KeyError)

    no key matched and no default given



21
22
23
24
25
26
27
28
29
30
# File 'lib/core_ext/hash.rb', line 21

def metch(search, default=:__n_o_n_e__)
  fetch search
rescue KeyError
  each do |key, value|
    next unless key.is_a? Regexp
    return value if key.match? search
  end
  raise(KeyError, "no match found: #{search.inspect}") if default == :__n_o_n_e__
  default
end

#to_remarksString?

Compile a titles/texts hash to remarks Markdown string

Examples:

{ name: 'foobar', ignore: => nil, 'count/quantité' => 3 }.to_remarks
# => "NAME\nfoobar\n\nCOUNT/QUANTITÉ\n3"
{ ignore: nil, ignore_as_well: "" }.to_remarks
# => nil

Returns:

  • (String, nil)

    compiled remarks



41
42
43
44
45
46
# File 'lib/core_ext/hash.rb', line 41

def to_remarks
  map { |k, v| "**#{k.to_s.upcase}**\n#{v}" unless v.blank? }.
    compact.
    join("\n\n").
    blank_to_nil
end