Best way to convert strings to symbols in hash

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

    In Rails you can use:

    {'g'=> 'a', 2 => {'v' => 'b', 'x' => { 'z' => 'c'}}}.deep_symbolize_keys!
    

    Converts to:

    {:g=>"a", 2=>{:v=>"b", :x=>{:z=>"c"}}}
    
    0 讨论(0)
  • 2020-11-27 09:55

    if you're using Rails, it is much simpler - you can use a HashWithIndifferentAccess and access the keys both as String and as Symbols:

    my_hash.with_indifferent_access 
    

    see also:

    http://api.rubyonrails.org/classes/ActiveSupport/HashWithIndifferentAccess.html


    Or you can use the awesome "Facets of Ruby" Gem, which contains a lot of extensions to Ruby Core and Standard Library classes.

      require 'facets'
      > {'some' => 'thing', 'foo' => 'bar'}.symbolize_keys
        =>  {:some=>"thing", :foo=>"bar}
    

    see also: http://rubyworks.github.io/rubyfaux/?doc=http://rubyworks.github.io/facets/docs/facets-2.9.3/core.json#api-class-Hash

    0 讨论(0)
  • 2020-11-27 09:55

    How about this:

    my_hash = HashWithIndifferentAccess.new(YAML.load_file('yml'))
    
    # my_hash['key'] => "val"
    # my_hash[:key]  => "val"
    
    0 讨论(0)
  • 2020-11-27 09:55
    ruby-1.9.2-p180 :001 > h = {'aaa' => 1, 'bbb' => 2}
     => {"aaa"=>1, "bbb"=>2} 
    ruby-1.9.2-p180 :002 > Hash[h.map{|a| [a.first.to_sym, a.last]}]
     => {:aaa=>1, :bbb=>2}
    
    0 讨论(0)
  • 2020-11-27 09:56

    If you are using json, and want to use it as a hash, in core Ruby you can do it:

    json_obj = JSON.parse(json_str, symbolize_names: true)
    

    symbolize_names: If set to true, returns symbols for the names (keys) in a JSON object. Otherwise strings are returned. Strings are the default.

    Doc: Json#parse symbolize_names

    0 讨论(0)
  • 2020-11-27 09:57

    This is my one liner for nested hashes

    def symbolize_keys(hash)
      hash.each_with_object({}) { |(k, v), h| h[k.to_sym] = v.is_a?(Hash) ? symbolize_keys(v) : v }
    end
    
    0 讨论(0)
提交回复
热议问题