Update deep_symbolize_keys is in rails 4
Could not find it elsewhere, so here it is: recursive_symbolize_keys, that will symbolize all keys inside a hash and its nested hashes.
Hash extension
class Hash def recursive_symbolize_keys! symbolize_keys! # symbolize each hash in .values values.each{|h| h.recursive_symbolize_keys! if h.is_a?(Hash) } # symbolize each hash inside an array in .values values.select{|v| v.is_a?(Array) }.flatten.each{|h| h.recursive_symbolize_keys! if h.is_a?(Hash) } self end end
Or standalone
def recursive_symbolize_keys! hash hash.symbolize_keys! hash.values.select{|v| v.is_a? Hash}.each{|h| recursive_symbolize_keys!(h)} end
# You could add that method to Hash, something like this (untested):
class Hash
def recursive_symbolize_keys!
symbolize_keys!
values.select { |v| v.is_a?(Hash) }.each { |h| h.recursive_symbolize_keys! }
end
end
Then you could call it like this: some_hash.recursive_symbolize_keys!
yep, I used the code for a plugin and did not want to write an extension to hash, but your solutions looks good for that!
You could also add a self at the end of the method to return the hash itself:
class Hash
def recursive_symbolize_keys!
symbolize_keys!
values.select { |v| v.is_a?(Hash) }.each { |h| h.recursive_symbolize_keys! }
self
end
end
I tweaked the code a little bit to also convert any hashes in arrays
class Hash
# https://pragmatig.wordpress.com/2009/04/14/recursive-symbolize_keys/
def recursive_symbolize_keys!
symbolize_keys!
# Loop through each value of this hash, if the value is a hash then symbolize that value
values.select { |v| v.is_a?(Hash) }.each { |h| h.recursive_symbolize_keys! }
# Loop through each value of this hash, if there is an array than check if each array value is a hash
values.select { |v| v.is_a?(Array) }.each { |a| a.each {|aa| aa.recursive_symbolize_keys! if aa.is_a?(Hash) } }
self
end
end
i cleaned it up a little, but still some duplication left (hope it still works as you intended )
Works for me, symbolizing a yml config file. Many thanks.
Thanks.
I know I’m a bit late to the party. This is recursive, but if you have an array of values with hashes then they aren’t converted:
def recursive_symbolize_keys! hash
hash.symbolize_keys!
hash.values.each{|h|
if Array === h
h.each{|vv| recursive_symbolize_keys!(vv) if Hash === vv }
elsif Hash === h
recursive_symbolize_keys!(h)
end
}
end
i think this needs a proper gist with tests so we can determine which version is best 🙂
Thanks– just what I was looking for!
If you’re using Rails, they’ve added deep versions for both symbolize_keys! and stringify_keys!. Check out https://github.com/rails/rails/pull/6060
Thanks for the info, great to see that they added that 😀