Method: HashTools#deep_fetch

Defined in:
lib/hash_tools.rb

#deep_fetch(hash, path, separator: FWD_SLASH, &default_blk) ⇒ Object

Fetch a deeply-nested hash key from a hash, using a String representing a path

deep_fetch({
  'a' => {
    'b' => {
      'c' => value}}
}, 'a/b/c') #=> value

numbers for deeply nested arrays (‘foo/0/bar’)

Parameters:

  • hash (Hash)

    the (potentially deep) string-keyed Hash to fetch the value from

  • path (String)

    the path to the item in hash. The path may contain

  • separator (String) (defaults to: FWD_SLASH)

    the path separator, defaults to ‘/’

  • default_blk

    The default value block for when there is no value.

Returns:

  • the fetched value or the value of the default_block



23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/hash_tools.rb', line 23

def deep_fetch(hash, path, separator: FWD_SLASH, &default_blk)
  keys = path.split(separator)
  keys.inject(hash) do |hash_or_array, k|
    if !hash_or_array.respond_to?(:fetch)
      raise "#{hash_or_array.inspect} does not respond to #fetch"
    elsif hash_or_array.is_a?(Array) && k =~ INT_KEY_RE
      hash_or_array.fetch(k.to_i, &default_blk)
    else
      hash_or_array.fetch(k, &default_blk)
    end
  end
end