Best way to convert strings to symbols in hash

前端 未结 30 3058
借酒劲吻你
借酒劲吻你 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条回答
  •  猫巷女王i
    2020-11-27 10:04

    Here's a better method, if you're using Rails:

    params.symbolize_keys

    The end.

    If you're not, just rip off their code (it's also in the link):

    myhash.keys.each do |key|
      myhash[(key.to_sym rescue key) || key] = myhash.delete(key)
    end
    

提交回复
热议问题