deep_symbolize_keys
- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3
- 2.1.0
- 2.2.1
- 2.3.8
- 3.0.0
- 3.0.9
- 3.1.0
- 3.2.1
- 3.2.8
- 3.2.13
- 4.0.2 (0)
- 4.1.8 (38)
- 4.2.1 (0)
- 4.2.7 (0)
- 4.2.9 (0)
- 5.0.0.1 (0)
- 5.1.7 (0)
- 5.2.3 (0)
- 6.0.0 (0)
- 6.1.3.1 (0)
- 6.1.7.7 (0)
- 7.0.0 (0)
- 7.1.3.2 (0)
- 7.1.3.4 (0)
- What's this?
deep_symbolize_keys()
public
Returns a new hash with all keys converted to symbols, as long as they respond to to_sym. This includes the keys from the root hash and from all nested hashes and arrays.
hash = { 'person' => { 'name' => 'Rob', 'age' => '28' } } hash.deep_symbolize_keys # => {:person=>{:name=>"Rob", :age=>"28"}}
Does not symbolize hashes in nested arrays
If you have a nested structure containing arrays of hashes, you still need to do that on your own, eg.
module SymbolizeHelper def symbolize_recursive(hash) {}.tap do |h| hash.each { |key, value| h[key.to_sym] = map_value(value) } end end def map_value(thing) case thing when Hash symbolize_recursive(thing) when Array thing.map { |v| map_value(v) } else thing end end end
Or, if you want to get really fancy with Ruby refinements (YMMV), one could do
module SymbolizeHelper extend self def symbolize_recursive(hash) {}.tap do |h| hash.each { |key, value| h[key.to_sym] = transform(value) } end end private def transform(thing) case thing when Hash; symbolize_recursive(thing) when Array; thing.map { |v| transform(v) } else; thing end end refine Hash do def deep_symbolize_keys SymbolizeHelper.symbolize_recursive(self) end end end
And later say
using SymbolizeHelper # augmented Hash#deep_symbolize_keys is now available
Works even on nested structures
@EdvardM added a note years ago saying this does not symbolize the keys of deeply nested hashes, which may have been the case for whatever version of ruby was available at the time, but in 4+, it definitely does work as described:
hash = {"a" => :a, "b" => {z: [[{"c" => 3}, {"c" => 4}], []]}} hash.deep_symbolize_keys => {:a=>:a, :b=>{:z=>[[{:c=>3}, {:c=>4}], []]}}