How to Check If a Hash Key Exists in Ruby

09/24/2021

Contents

In this article, you will learn how to check if a hash key exists in Ruby.

Checking if a hash key exists

In Ruby, you can check if a hash key exists using several methods. Here are some of the most common ways to achieve this:

Using the has_key? method

The has_key? method checks if a hash contains the given key and returns true or false depending on whether the key is present or not. You can also use the alias method key? for the same purpose.

Here’s an example:

my_hash = { "name" => "John", "age" => 30 }

if my_hash.has_key?("name")
  puts "The key 'name' exists"
else
  puts "The key 'name' does not exist"
end

Output:

The key 'name' exists

Using the key method

The key method returns the key for a given value. If the value is not present in the hash, it returns nil.

Here’s an example:

my_hash = { "name" => "John", "age" => 30 }

if my_hash.key("John")
  puts "The key for 'John' exists"
else
  puts "The key for 'John' does not exist"
end

Output:

The key for 'John' exists

Using the include? method

The include? method checks if a hash contains the given key and returns true or false depending on whether the key is present or not.

Here’s an example:

my_hash = { "name" => "John", "age" => 30 }

if my_hash.include?("name")
  puts "The key 'name' exists"
else
  puts "The key 'name' does not exist"
end

Output:

The key 'name' exists

Using the key? method

The key? method is an alias for the has_key? method and works the same way. It checks if a hash contains the given key and returns true or false depending on whether the key is present or not.

Here’s an example:

my_hash = { "name" => "John", "age" => 30 }

if my_hash.key?("name")
  puts "The key 'name' exists"
else
  puts "The key 'name' does not exist"
end

Output:

The key 'name' exists

Using the member? method

The member? method checks if a hash contains the given key and returns true or false depending on whether the key is present or not.

Here’s an example:

my_hash = { "name" => "John", "age" => 30 }

if my_hash.member?("name")
  puts "The key 'name' exists"
else
  puts "The key 'name' does not exist"
end

Output:

The key 'name' exists