Class: Hash

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

Instance Method Summary collapse

Instance Method Details

#value_from_nested_key(key) ⇒ Object

‘x’=>{‘y’=>{‘z’=>1}.value_from_nested_key(‘x[z]’) => 1



3
4
5
6
7
8
9
10
11
12
13
14
15
# File 'lib/helpful_fields/core_ext/hash.rb', line 3

def value_from_nested_key(key)
  if key.to_s.include?('[')
    match, first, nesting = key.to_s.match(/(.+?)\[(.*)\]/).to_a
    value = self[first]
    nesting.split('][').each do |part|
      return nil unless value.is_a?(Hash)
      value = value[part]
    end
    value
  else
    self[key]
  end
end