Best way to convert strings to symbols in hash

前端 未结 30 2977
借酒劲吻你
借酒劲吻你 2020-11-27 09:30

What\'s the (fastest/cleanest/straightforward) way to convert all keys in a hash from strings to symbols in Ruby?

This would be handy when parsing YAML.



        
30条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 10:02

    A modification to @igorsales answer

    class Object
      def deep_symbolize_keys
        return self.inject({}){|memo,(k,v)| memo[k.to_sym] = v.deep_symbolize_keys; memo} if self.is_a? Hash
        return self.inject([]){|memo,v    | memo           << v.deep_symbolize_keys; memo} if self.is_a? Array
        return self
      end
    end
    

提交回复
热议问题