Module: Corefines::Hash::SymbolizeKeys

Defined in:
lib/corefines/hash.rb

Instance Method Summary collapse

Instance Method Details

#symbolize_keysHash

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.


289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/corefines/hash.rb', line 289

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:


289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/corefines/hash.rb', line 289

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