DEV Community

Paul Marclay
Paul Marclay

Posted on

Ruby - With indifferent access

Image description

You know that when you deal with external APIs you may encounter anything, even the Frankenstein's monster as a response... (even when they tell you they will response only an inoffensive JSON)

I mean, in the response you could get a hash with some keys at different depths and perhaps in some cases you could have keys as strings or as symbols.

Image description

So you will be alternating among them in your code, something like

Image description

In other case, let's suppose you try access to the user name just using symbols or strings you will receive a nil response, let's check

Image description

Don't say I didn't tell you, we couldn't access the information, fortunately, here is when ".with_indifferent_access" method comes to the rescue!
It is a method of ActiveSupport::HashWithIndifferentAccess class.
And let's check how can we use it modifying the above example

Image description

Or you could just use it without dig

Image description

And that's all Ruby mates,
Thanks for reading!

Top comments (0)