Platinum Partner

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

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
{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}