Best way to convert strings to symbols in hash

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

提交回复
热议问题