DEV Community

Cover image for Extract key or value from hash in Ruby on Rails
Prabin Poudel for Truemark Technology

Posted on • Originally published at thedevpost.com

3 1

Extract key or value from hash in Ruby on Rails

When I was recently working in one of the client project, I had to communicate with external mariadb server to store records from react/rails app, that means I would get activerecord hash from our app which I had to convert to pure sql query and send it to external server for storing.

If you have worked with sql queries previously then you must know that keys and values must be separated for insert operations like

INSERT INTO users (first_name, last_name, email) VALUES (John, Doe, john@email.com)
Enter fullscreen mode Exit fullscreen mode

I could convert attributes to hash easily using as_json to get the format {"first_name"=>"John", "last_name"=>"Doe", "email"=>"john@email.com"}. But I had to extract keys and values separately so that attributes can be accurately formatted and ready for insert and update operations. Let me show you how I extracted keys and values from the hash and formatted them as required for the operations.

Let's assume we have: user = {"first_name"=>"John", "last_name"=>"Doe", "email"=>"john@email.com"}

Extract single key or value

If we only want email

// For key
user.extract!("email").keys # ["email"]

// For value

# with extract
user.extract!("email").values # ["john@email.com"]

# simply
user['email'] # "john@email.com"
Enter fullscreen mode Exit fullscreen mode

Extract multiple keys or values

If we want first_name and last_name but not email

// For keys
user.extract!(*["first_name", "last_name"]).keys # ["first_name", "last_name"]

// For values
user.extract!(*["first_name", "last_name"]).values # ["John", "Doe"]
Enter fullscreen mode Exit fullscreen mode

Extract all keys or values

// For keys
user.keys # ["first_name", "last_name", "email"]

// For values
user.values # ["John", "Doe", "john@email.com"]

Enter fullscreen mode Exit fullscreen mode

Do you know more elegant or alternative way to extract keys and values from hashes? Please enlighten and guide us with your precious comment below if you do.

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