Class: Hash
- Inherits:
-
Object
- Object
- Hash
- Defined in:
- lib/hash_extensions.rb
Instance Method Summary collapse
-
#dig(*path) ⇒ Object
Search for key path in hash.
-
#values_for(key) ⇒ Object
Search the Hash deeply for all values matching the
key.
Instance Method Details
#dig(*path) ⇒ Object
Search for key path in hash
Examples
{ a: { b: :c } }.dig(:a, :b) # => :c
{ a: { 'b' => :c } }.dig(:a, :b) # => :c
{ a: { b: :c } }.dig(:a, :c) # => nil
11 12 13 14 15 |
# File 'lib/hash_extensions.rb', line 11 def dig(*path) path.reduce(self) do |location, key| location.respond_to?(:keys) ? location.stringify_keys[key.to_s] : nil end end |
#values_for(key) ⇒ Object
Search the Hash deeply for all values matching the key.
Examples
{ a: :b, c: { a: '1', d: :e } }.values_for('a') # => [:b, '1']
22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/hash_extensions.rb', line 22 def values_for(key) found_values = [] self.each do |k, v| found_values << v if k.to_s == key.to_s if v.is_a? Hash found_values << v.values_for(key) end end found_values.flatten.compact end |