DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Convert All Keys In Multidimensional Hashes In Ruby (non-recursive Method)

04.25.2012
| 5159 views |
  • submit to reddit
        Code 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