recursive symbolize_keys

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

12 thoughts on “recursive symbolize_keys

  1. # 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!

  2. 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

  3. 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

  4. 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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s