How to elegantly symbolize_keys for a 'nested' hash

后端 未结 6 2199
無奈伤痛
無奈伤痛 2021-02-06 20:46

Consider the following code:

  hash1 = {\"one\" => 1, \"two\" => 2, \"three\" => 3}
  hash2 = hash1.reduce({}){ |h, (k,v)| h.merge(k => hash1) }
  ha         


        
6条回答
  •  渐次进展
    2021-02-06 21:20

    I can suggest something like this:

    class Object
      def deep_symbolize_keys
        self
      end
    end
    
    class Hash
      def deep_symbolize_keys
        symbolize_keys.tap { |h| h.each { |k, v| h[k] = v.deep_symbolize_keys } }
      end
    end
    
    {'a'=>1, 'b'=>{'c'=>{'d'=>'d'}, e:'f'}, 'g'=>1.0, 'h'=>nil}.deep_symbolize_keys
    # => {:a=>1, :b=>{:c=>{:d=>"d"}, :e=>"f"}, :g=>1.0, :h=>nil} 
    

    You can also easily extend it to support Arrays:

    class Array
      def deep_symbolize_keys
        map(&:deep_symbolize_keys)
      end
    end
    
    {'a'=>1, 'b'=>[{'c'=>{'d'=>'d'}}, {e:'f'}]}.deep_symbolize_keys
    # => {:a=>1, :b=>[{:c=>{:d=>"d"}}, {:e=>"f"}]}
    

提交回复
热议问题