Class: Hash

Inherits:
Object show all
Defined in:
lib/core_ext/deep_fetch.rb,
lib/core_ext/stringify_keys.rb

Instance Method Summary collapse

Instance Method Details

#deep_fetch(key, default = nil) ⇒ Object



4
5
6
7
8
# File 'lib/core_ext/deep_fetch.rb', line 4

def deep_fetch(key, default = nil)
  keys = key.to_s.split('.')
  value = dig(*keys) rescue default
  value.nil? ? default : value  # value can be false (Boolean)
end

#stringify_keysObject

Returns a new hash with all keys converted to strings.

hash = { name: 'Rob', age: '28' }

hash.stringify_keys
# => {"name"=>"Rob", "age"=>"28"}


18
19
20
# File 'lib/core_ext/stringify_keys.rb', line 18

def stringify_keys
  transform_keys(&:to_s)
end

#transform_keysObject

Stolen from ActiveSupport



3
4
5
6
7
8
9
10
# File 'lib/core_ext/stringify_keys.rb', line 3

def transform_keys
  return enum_for(:transform_keys) { size } unless block_given?
  result = {}
  each_key do |key|
    result[yield(key)] = self[key]
  end
  result
end