The Ruby has_key? method simply checks to see if a hash has a specific key or not. If it does, true will be returned. If the key is not found, false will be returned.

some_hash = {"first_name" => "David", "last_name" => "Smith"}

puts some_hash.has_key? "first_name"

#Output
true

The has_key? method is pretty straightforward but can be really useful when trying to find information stored in a hash.

Let’s look at some more examples of the has_key? method.

some_hash = {"id" => "1", "first_name" => "David", "last_name" => "Smith", "age" => "45"}

puts some_hash.has_key? "first_name"
puts some_hash.has_key? "David"
puts some_hash.has_key? "last_name"
puts some_hash.has_key? "age"
puts some_hash.has_key? ""

#Output
true
false
true
true
false

Let’s take a look at the has_value? method in Ruby to get the other values in our hash.

Check If Value Exists in Hash Using the Ruby has_value? Method

We looked at the has_key? method above to see if a certain key was contained in our hash. Now we can use the has_value? method to see if certain values are contained in our hash.

some_hash = {"first_name" => "David", "last_name" => "Smith"}

puts some_hash.has_value? "David"

#Output
true

Let’s run the same examples above, but this time check for certain values that might be contained in the hash.

some_hash = {"id" => "1", "first_name" => "David", "last_name" => "Smith", "age" => "45"}

puts some_hash.has_value? "first_name"
puts some_hash.has_value? "David"
puts some_hash.has_value? "last_name"
puts some_hash.has_value? "45"
puts some_hash.has_value? 45

#Output
false
true
false
true
false

Hopefully this article has been useful for you to learn how to the Ruby has_key? method works.

Categorized in:

Ruby,

Last Update: March 1, 2024