Class: Hash

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

Direct Known Subclasses

HashWithIndifferentAccess

Instance Method Summary collapse

Instance Method Details

#symbolize_keys(recursive = false) ⇒ Object

Return a new hash with all keys converted to symbols, as long as they respond to to_sym. If recursive is set to true, then keys at all levels will be symbolized.



5
6
7
# File 'lib/hash_symbolizer/core_ext/hash.rb', line 5

def symbolize_keys(recursive = false)
  dup.symbolize_keys!(recursive)
end

#symbolize_keys!(recursive = false) ⇒ Object

Destructively convert all keys to symbols, as long as they respond to to_sym. If recursive is set to true, then keys at all levels will be symbolized.



12
13
14
15
16
17
18
19
# File 'lib/hash_symbolizer/core_ext/hash.rb', line 12

def symbolize_keys!(recursive = false)
  keys.each do |key|
    value = delete(key)
    key = key.respond_to?(:to_sym) ? key.to_sym : key
    self[key] = (recursive && value.is_a?(Hash)) ? value.dup.symbolize_keys!(recursive) : value
  end
  self
end