Search code examples
rubyhashmap

Best way to convert strings to symbols in hash


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.

my_hash = YAML.load_file('yml')

I'd like to be able to use:

my_hash[:key] 

Rather than:

my_hash['key']

Solution

  • 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