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

10 comments
Comments feed for this article
2009-05-02 at 18:08:14
zubin789
# 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!
2009-05-02 at 18:44:03
pragmatig
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!
2009-06-03 at 12:41:54
Paolo Dona
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
2010-01-05 at 23:30:45
Eric Peters
I tweaked the code a little bit to also convert any hashes in arrays
class Hash
# http://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
2010-01-06 at 8:18:17
pragmatig
i cleaned it up a little, but still some duplication left (hope it still works as you intended )
2010-09-22 at 16:08:09
Paul Vudmaska
Works for me, symbolizing a yml config file. Many thanks.
2010-12-16 at 16:44:22
Roberto
Thanks.
2011-01-11 at 20:19:23
matt
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
2011-01-12 at 6:34:58
pragmatig
i think this needs a proper gist with tests so we can determine which version is best
2011-06-16 at 21:35:15
jawsh222
Thanks– just what I was looking for!