Best way to convert strings to symbols in hash

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

提交回复
热议问题