How to check if hash has key in Ruby (2024)

With Ruby, there are some cases where you want to check if a given key is already in the hash.

If you’re new to hashes, I wrote a basic blog article about Ruby hashes.

Is checking the key of a hash already exists in the Ruby API ?

What if you want to check that a given hash has a given key ? Before writing any code, the first thing you should think about is “does this already exist somewhere in the API” ?

It’s very uncommon that a utility function is missing - excerpt may be for JavaScript, for historical reasons.

But not for Ruby, even more in a Ruby-on-Rails environment.

Ruby core : a one-liner way to check if key exists

For those who already know Ruby, here is the quick answer

1
$> my_hash.key?("my_key")

Ruby : Check presence of key by casting to a boolean

Start the Ruby console (in a Rails project, enter “bin/rails console”).

Note by the way that the String 'a' is considered as a different key than symbol a:

I want to check that the key belongs to my_hash, so a naive approach would be to use the double !! that will convert any value to a boolean. It’s a trick used in other languages like JavaScript.

12345678
$> my_hash[:b]'some_value'$> my_hash[:c]nil$> !!my_hash[:b]false$> !!my_hash[:c]true

A more expressive way to check presence of a specific key of a Ruby hash

The Ruby hash has an expressive API for the most common use cases. You can use the .key? method instead of the !! seen above.

It’s a lot more readable for other developers.

Examples :

12345678
$> my_hash[:b]'some_value'$> my_hash[:c]nil$> my_hash.key?[:b]false$> my_hash.key?[:c]true

Ruby-on-Rails : check if hash has key

You can use the .has_key? as well. I prefer this solution because it makes the intent a lot clearer. Since you expect a boolean, starting the method by is_ or has_/have_ is better.

12345678
$> my_hash[:b]'some_value'$> my_hash[:c]nil$> my_hash.has_key?[:b]false$> my_hash.has_key?[:c]true

The most robust possible answer

So now what if you’re not quite sure about the hash you’re checking.

Case one : You’re not sure if the keys are symbols or not - think about a hash that is extracted from a remote API.

12
$> my_hash.deep_symbolize_keys.try(:key?, :a)true

Case two : you’re not sure if it is actually a hash (could be nil or a wrong type)

12
$> my_hash.try(:key?, :a)true

Note that this could be considered as over-engineering, depending on the context.

Conclusion

Checking if a hash has a key in Ruby is pretty straightforward, all you need is to pay a little attention in which context you’re writing this verification.

See also this SO question.

This post is licensed under CC BY 4.0 by the author.

How to check if hash has key in Ruby (2024)
Top Articles
Jumbo Loan Limits By State | Bankrate
Refinance Requirements: 6 Things You’ll Need | Quicken Loans
Where To Go After Howling Pit Code Vein
O'reilly's Auto Parts Closest To My Location
Gomoviesmalayalam
Quick Pickling 101
1970 Chevrolet Chevelle SS - Skyway Classics
Free Atm For Emerald Card Near Me
Koordinaten w43/b14 mit Umrechner in alle Koordinatensysteme
Cosentyx® 75 mg Injektionslösung in einer Fertigspritze - PatientenInfo-Service
Rainfall Map Oklahoma
Raid Guides - Hardstuck
The Weather Channel Facebook
Oxford House Peoria Il
Echo & the Bunnymen - Lips Like Sugar Lyrics
Local Collector Buying Old Motorcycles Z1 KZ900 KZ 900 KZ1000 Kawasaki - wanted - by dealer - sale - craigslist
Nebraska Furniture Tables
Vanessa West Tripod Jeffrey Dahmer
Haunted Mansion Showtimes Near Millstone 14
U Arizona Phonebook
Forum Phun Extra
Ahn Waterworks Urgent Care
Barber Gym Quantico Hours
Clare Briggs Guzman
Never Give Up Quotes to Keep You Going
Rs3 Eldritch Crossbow
All Obituaries | Verkuilen-Van Deurzen Family Funeral Home | Little Chute WI funeral home and cremation
Integer Division Matlab
Parkeren Emmen | Reserveren vanaf €9,25 per dag | Q-Park
Soul Eater Resonance Wavelength Tier List
How do you get noble pursuit?
Shiny Flower Belinda
Wells Fargo Bank Florida Locations
Landing Page Winn Dixie
Khatrimmaza
About Us | SEIL
New York Rangers Hfboards
Vanessa West Tripod Jeffrey Dahmer
Powerspec G512
Magicseaweed Capitola
Best Restaurant In Glendale Az
Jammiah Broomfield Ig
Ohio Road Construction Map
Rocket League Tracker: A useful tool for every player
Theatervoorstellingen in Nieuwegein, het complete aanbod.
Egg Inc Wiki
Shiftselect Carolinas
Mikayla Campinos Alive Or Dead
Rubmaps H
Fresno Craglist
Raley Scrubs - Midtown
Invitation Quinceanera Espanol
Latest Posts
Article information

Author: Allyn Kozey

Last Updated:

Views: 6040

Rating: 4.2 / 5 (43 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Allyn Kozey

Birthday: 1993-12-21

Address: Suite 454 40343 Larson Union, Port Melia, TX 16164

Phone: +2456904400762

Job: Investor Administrator

Hobby: Sketching, Puzzles, Pet, Mountaineering, Skydiving, Dowsing, Sports

Introduction: My name is Allyn Kozey, I am a outstanding, colorful, adventurous, encouraging, zealous, tender, helpful person who loves writing and wants to share my knowledge and understanding with you.