Best way to convert strings to symbols in hash

前端 未结 30 2984
借酒劲吻你
借酒劲吻你 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:09

    This is not exactly a one-liner, but it turns all string keys into symbols, also the nested ones:

    def recursive_symbolize_keys(my_hash)
      case my_hash
      when Hash
        Hash[
          my_hash.map do |key, value|
            [ key.respond_to?(:to_sym) ? key.to_sym : key, recursive_symbolize_keys(value) ]
          end
        ]
      when Enumerable
        my_hash.map { |value| recursive_symbolize_keys(value) }
      else
        my_hash
      end
    end
    

提交回复
热议问题