Best way to convert strings to symbols in hash

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

    In ruby I find this to be the most simple and easy to understand way to turn string keys in hashes to symbols :

    my_hash.keys.each { |key| my_hash[key.to_sym] = my_hash.delete(key)}
    

    For each key in the hash we call delete on it which removes it from the hash (also delete returns the value associated with the key that was deleted) and we immediately set this equal to the symbolized key.

提交回复
热议问题