Module: Corefines::Hash::SymbolizeKeys

Defined in:
lib/corefines/hash.rb

Instance Method Summary collapse

Instance Method Details

#symbolize_keys ⇒ Hash

Returns a new hash with all keys converted to symbols, as long as they respond to to_sym.

Examples:

hash = { 'name' => 'Lindsey', :born => 1986 }
hash.symbolize_keys # => { :name => 'Lindsey', :born => 1986 }
hash # => { 'name' => 'Lindsey', :born => 1986 }

Returns:

  • (Hash) —

    a new hash with all keys converted to symbols, as long as they respond to to_sym.



297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/corefines/hash.rb', line 297

module SymbolizeKeys
  refine ::Hash do
    def symbolize_keys
      each_with_object(dup.clear) do |(key, value), hash|
        hash[(key.to_sym rescue key)] = value
      end
    end

    def symbolize_keys!
      keys.each do |key|
        self[(key.to_sym rescue key)] = delete(key)
      end
      self
    end
  end
end

#symbolize_keys! ⇒ Hash

Converts all keys to symbols, as long as they respond to to_sym. Same as #symbolize_keys, but modifies self.

Returns:



297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/corefines/hash.rb', line 297

module SymbolizeKeys
  refine ::Hash do
    def symbolize_keys
      each_with_object(dup.clear) do |(key, value), hash|
        hash[(key.to_sym rescue key)] = value
      end
    end

    def symbolize_keys!
      keys.each do |key|
        self[(key.to_sym rescue key)] = delete(key)
      end
      self
    end
  end
end