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

后端 未结 15 1845
不思量自难忘°
不思量自难忘° 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:30

    Victor Moroz provided a lovely answer for the simple recursive case, but it won't process hashes that are nested within nested arrays:

    hash = { "a" => [{ "b" => "c" }] }
    s2s[hash] #=> {:a=>[{"b"=>"c"}]}
    

    If you need to support hashes within arrays within hashes, you'll want something more like this:

    def recursive_symbolize_keys(h)
      case h
      when Hash
        Hash[
          h.map do |k, v|
            [ k.respond_to?(:to_sym) ? k.to_sym : k, recursive_symbolize_keys(v) ]
          end
        ]
      when Enumerable
        h.map { |v| recursive_symbolize_keys(v) }
      else
        h
      end
    end
    

提交回复
热议问题