Best way to convert strings to symbols in hash

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

    Similar to previous solutions but written a bit differently.

    • This allows for a hash that is nested and/or has arrays.
    • Get conversion of keys to a string as a bonus.
    • Code does not mutate the hash been passed in.

      module HashUtils
        def symbolize_keys(hash)
          transformer_function = ->(key) { key.to_sym }
          transform_keys(hash, transformer_function)
        end
      
        def stringify_keys(hash)
          transformer_function = ->(key) { key.to_s }
          transform_keys(hash, transformer_function)
        end
      
        def transform_keys(obj, transformer_function)
          case obj
          when Array
            obj.map{|value| transform_keys(value, transformer_function)}
          when Hash
            obj.each_with_object({}) do |(key, value), hash|
              hash[transformer_function.call(key)] = transform_keys(value, transformer_function)
            end
          else
            obj
          end
        end
      end
      

提交回复
热议问题