module Hashie::Extensions::StringifyKeys

Extends a Hash with the ability to convert its keys to strings.

@example Extend a pre-existing Hash object

hash = { test: 'value' }
hash.extend(Hashie::Extensions::StringifyKeys)
hash.stringify_keys!
hash # => { 'test' => 'value' }

@example Create a Hash class with this capability

class StringifyingHash < Hash
  include Hashie::Extensions::StringifyKeys
end

hash = StringifyingHash.new
hash[:test] = 'value'
hash.stringify_keys!
hash # => { 'test' => 'value' }

@example Use the module function to stringify keys in a hash

hash = { test: 'value' }
Hashie::Extensions::StringifyKeys.stringify_keys!(hash)
hash # => { 'test' => 'value' }

Public Instance Methods

stringify_keys() click to toggle source

Returns a shallow copy with all keys recursively converted to strings. Nested hashes and arrays are shared with the original and are modified.

@example Copy a flat hash without modifying the original

test = { abc: 'def' }
test.extend(Hashie::Extensions::StringifyKeys)
test.stringify_keys # => { 'abc' => 'def' }
test # => { abc: 'def' }

@example Nested values are shared, not deep copied

test = { abc: [{ def: 'value' }] }
test.extend(Hashie::Extensions::StringifyKeys)
test.stringify_keys # => { 'abc' => [{ 'def' => 'value' }] }
test # => { abc: [{ 'def' => 'value' }] }

@api public @return [Hash] a shallow copy with stringified keys

# File lib/hashie/extensions/stringify_keys.rb, line 60
def stringify_keys
  StringifyKeys.stringify_keys(self)
end
stringify_keys!() click to toggle source

Converts all keys in the hash and nested hashes and arrays to strings.

@example Convert keys in place

test = { abc: [{ def: 'value' }] }
test.extend(Hashie::Extensions::StringifyKeys)
test.stringify_keys!
test # => { 'abc' => [{ 'def' => 'value' }] }

@api public @return [Hash] the receiver with its keys converted to strings

# File lib/hashie/extensions/stringify_keys.rb, line 38
def stringify_keys!
  StringifyKeys.stringify_keys!(self)
  self
end