Convert Ruby hash keys to symbols
Problem
you have a hash with string keys but want to access them with symbols instead.
You have:
myhash = {"name" => "James", "email" => "james@hotmail.com"}
if you try to access the hash above with symbols, you'll get nil
myhash[:name] #nil
however
myhash['name'] # "James"
Solution
There are two methods that can help you. One is symbolize_keys! which only symbolizes first level keys and withindifferentaccess which symbolizes recursively.
indifferent_hash = myhash.with_indifferent_access
indifferent_hash[:name] # "James"
indifferent_hash['name'] #"James"
or
myhash.symbolize_keys![:name] # "James"
Written by Bashir Eghbali
Related protips
1 Response
of course this works only in rails, thanks to ActiveSupport - https://github.com/rails/rails/blob/a37b90caf4262fd0ef4141e1e15cca3745af6912/activesupport/lib/active_support/hash_with_indifferent_access.rb#L15
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Rails
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#