How do I convert a Ruby hash so that all of its keys are symbols?

后端 未结 15 1790
不思量自难忘°
不思量自难忘° 2020-12-04 19:01

I have a Ruby hash which looks like:

{ \"id\" => \"123\", \"name\" => \"test\" }

I would like to convert it to:

{ :id         


        
15条回答
  •  北海茫月
    2020-12-04 19:40

    You can also extend core Hash ruby class placing a /lib/hash.rb file :

    class Hash
      def symbolize_keys_deep!
        new_hash = {}
        keys.each do |k|
          ks    = k.respond_to?(:to_sym) ? k.to_sym : k
          if values_at(k).first.kind_of? Hash or values_at(k).first.kind_of? Array
            new_hash[ks] = values_at(k).first.send(:symbolize_keys_deep!)
          else
            new_hash[ks] = values_at(k).first
          end
        end
    
        new_hash
      end
    end
    

    If you want to make sure keys of any hash wrapped into arrays inside your parent hash are symbolized, you need to extend also array class creating a "array.rb" file with that code :

    class Array
      def symbolize_keys_deep!
        new_ar = []
        self.each do |value|
          new_value = value
          if value.is_a? Hash or value.is_a? Array
            new_value = value.symbolize_keys_deep!
          end
          new_ar << new_value
        end
        new_ar
      end
    end
    

    This allows to call "symbolize_keys_deep!" on any hash variable like this :

    myhash.symbolize_keys_deep!
    

提交回复
热议问题