Best way to convert strings to symbols in hash

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

    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}
    

提交回复
热议问题