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!

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more