Convert All Keys In Multidimensional Hashes In Ruby (non-recursive Method)
Join the DZone community and get the full member experience.
Join For FreeCode for converting all keys in a multidimensional Hash.
Works non-recursive, which should give better performance.
class Hash
def stringify_keys_deep
superhash = {0=>self}
hashes = [[superhash,0]]
while not hashes.empty?
outer_hash, outer_key = hashes.pop
outer_hash[outer_key] = outer_hash[outer_key].inject({}) do |hash, (key, value)|
key = key.to_s
hash[key] = value
hashes << [hash,key] if value.kind_of? Hash
hash
end
end
superhash[0]
end
def stringify_keys_deep!
self.replace(self.stringify_keys_recursive)
end
def symbolize_keys_deep
superhash = {0=>self}
hashes = [[superhash,0]]
while not hashes.empty?
outer_hash, outer_key = hashes.pop
outer_hash[outer_key] = outer_hash[outer_key].inject({}) do |hash, (key, value)|
key = key.to_sym rescue key || key
hash[key] = value
hashes << [hash,key] if value.kind_of? Hash
hash
end
end
superhash[0]
end
def symbolize_keys_deep!
self.replace(self.symbolize_keys_recursive)
end
end
Convert (command)
Opinions expressed by DZone contributors are their own.
Comments