Best way to convert strings to symbols in hash

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

    Since Ruby 2.5.0 you can use Hash#transform_keys or Hash#transform_keys!.

    {'a' => 1, 'b' => 2}.transform_keys(&:to_sym) #=> {:a => 1, :b => 2}
    

提交回复
热议问题