Sometimes, You may have stumbled across these cases why you got nil
value from accessing a hash.
For example
First case,
fruit = { name: "Grape", color: "purple" }
Then
fruit[:name]
=> "Grape"
fruit["name"]
=> nil
Second case,
fruit = { "name" => "Grape", "color" => "purple" }
Then
fruit[:name]
=> nil
fruit["name"]
=> "Grape"
These two examples show that you need to know the hash key's structure, whether it's a string or a symbol key, to access it correctly.
Or you can convert it by using symbolize_keys()
(returns a new hash with all keys converted to be symbols) and you can access it by using the symbol key.
Would it be better if we can access a hash either string or symbol keys?
Using with_indifferent_access()
For example
fruit = { name: "Grape", color: "purple" }.with_indifferent_access
fruit[:name]
=> "Grape"
fruit["name"]
=> "Grape"
It's pretty convenient because it ensures you get the value of the hash.
Reference: https://api.rubyonrails.org/classes/ActiveSupport/HashWithIndifferentAccess.html
Top comments (0)