module Hashie::Extensions::SymbolizeKeys
Extends a Hash with the ability to convert its keys to symbols. Keys that do not respond to to_sym are preserved.
@example Extend a pre-existing Hash object
hash = { 'test' => 'value' } hash.extend(Hashie::Extensions::SymbolizeKeys) hash.symbolize_keys! hash # => { test: 'value' }
@example Create a Hash class with this capability
class SymbolizableHash < Hash include Hashie::Extensions::SymbolizeKeys end hash = SymbolizableHash.new hash['test'] = 'value' hash.symbolize_keys! hash # => { test: 'value' }
@example Use the module function to symbolize keys in a hash
hash = { 'test' => 'value', 123 => 'number' } Hashie::Extensions::SymbolizeKeys.symbolize_keys!(hash) hash # => { test: 'value', 123 => 'number' }
Public Instance Methods
symbolize_keys()
click to toggle source
Returns a shallow copy with keys recursively converted to symbols. 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::SymbolizeKeys) test.symbolize_keys # => { abc: 'def' } test # => { 'abc' => 'def' }
@example Nested values are shared, not deep copied
test = { 'abc' => [{ 'def' => 'value' }] } test.extend(Hashie::Extensions::SymbolizeKeys) test.symbolize_keys # => { abc: [{ def: 'value' }] } test # => { 'abc' => [{ def: 'value' }] }
@api public @return [Hash] a shallow copy with symbolized keys
# File lib/hashie/extensions/symbolize_keys.rb, line 61 def symbolize_keys SymbolizeKeys.symbolize_keys(self) end
symbolize_keys!()
click to toggle source
Converts keys in the hash and nested hashes and arrays to symbols.
@example Convert keys in place
test = { 'abc' => [{ 'def' => 'value' }] } test.extend(Hashie::Extensions::SymbolizeKeys) test.symbolize_keys! test # => { abc: [{ def: 'value' }] }
@api public @return [Hash] the receiver with its keys symbolized where possible
# File lib/hashie/extensions/symbolize_keys.rb, line 39 def symbolize_keys! SymbolizeKeys.symbolize_keys!(self) self end