Best way to convert strings to symbols in hash

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

    Would something like the following work?

    new_hash = Hash.new
    my_hash.each { |k, v| new_hash[k.to_sym] = v }
    

    It'll copy the hash, but you won't care about that most of the time. There's probably a way to do it without copying all the data.

提交回复
热议问题