Best way to convert strings to symbols in hash

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

    Starting on Psych 3.0 you can add the symbolize_names: option

    Psych.load("---\n foo: bar") # => {"foo"=>"bar"}

    Psych.load("---\n foo: bar", symbolize_names: true) # => {:foo=>"bar"}

    Note: if you have a lower Psych version than 3.0 symbolize_names: will be silently ignored.

    My Ubuntu 18.04 includes it out of the box with ruby 2.5.1p57

提交回复
热议问题