DEV Community

Nuttee
Nuttee

Posted on

2

How to access a Hash either string or symbol keys

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay