Best way to convert strings to symbols in hash

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

    In Ruby >= 2.5 (docs) you can use:

    my_hash.transform_keys(&:to_sym)
    

    Using older Ruby version? Here is a one-liner that will copy the hash into a new one with the keys symbolized:

    my_hash = my_hash.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
    

    With Rails you can use:

    my_hash.symbolize_keys
    my_hash.deep_symbolize_keys 
    

提交回复
热议问题