DEV Community

loading...

How to access a Hash either string or symbol keys

nuttapon profile image Nuttee ・1 min read

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" }
Enter fullscreen mode Exit fullscreen mode

Then

fruit[:name]
=> "Grape"

fruit["name"]
=> nil
Enter fullscreen mode Exit fullscreen mode

Second case,

fruit = { "name" => "Grape", "color" => "purple" }
Enter fullscreen mode Exit fullscreen mode

Then

fruit[:name]
=> nil

fruit["name"]
=> "Grape"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

It's pretty convenient because it ensures you get the value of the hash.

Reference: https://api.rubyonrails.org/classes/ActiveSupport/HashWithIndifferentAccess.html

Discussion (0)

pic
Editor guide