paint-brush
How To Extract Key or Value From Hash in Ruby on Railsby@Kiran
6,322 reads
6,322 reads

How To Extract Key or Value From Hash in Ruby on Rails

by KiranJune 29th, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

How To Extract Key or Value From Hash in Ruby on Ruby on Rails? How To extract keys and values separately so that attributes can be accurately formatted and ready for insert and update operations. Do you know a more elegant or alternative way to extract keys or values from hashes? Please enlighten and guide us with your precious guide below if you do. This post was originally posted on DevPost.com by Kiran Content Writer at Truemark Technology. He is currently working with Truemark Tech.dev.
featured image - How To Extract Key or Value From Hash in Ruby on Rails
Kiran HackerNoon profile picture

When I was recently working in one of the client projects, 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 an 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, [email protected])

I could convert attributes to hash easily using

as_json
to get the format

{"first_name"=>"John", "last_name"=>"Doe", "email"=>"[email protected]"}

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"=>"[email protected]"}

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 # ["[email protected]"]

# simply
user['email'] # "[email protected]"

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"]

Extract all keys or values

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

// For values
user.values # ["John", "Doe", "[email protected]"]

Do you know a 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.

This post was originally posted on DevPost.