1. Introduction
In Ruby, a hash is a collection of key-value pairs. Often, you might need to verify if a particular key exists within a hash. This post will guide you through the process of checking if a key exists in a hash in Ruby.
2. Program Steps
1. Create a hash with key-value pairs.
2. Use the has_key? method or the key? method to check if the hash contains a particular key.
3. Print the result.
3. Code Program
# Creating a hash with some key-value pairs
book = {
"title" => "To Kill a Mockingbird",
"author" => "Harper Lee",
"year" => 1960,
"genre" => "Fiction"
}
# Key to be checked
key_to_check = "author"
# Check if the hash contains the key
key_exists = book.has_key?(key_to_check)
# Printing the result
if key_exists
puts "The key '#{key_to_check}' exists in the hash."
else
puts "The key '#{key_to_check}' does not exist in the hash."
end
Output:
The key 'author' exists in the hash.
Explanation:
1. A hash named book is created with four key-value pairs.
2. The has_key? method is invoked on the book hash, passing the key_to_check as an argument. This method returns true if the key exists and false otherwise.
3. Based on the return value of the has_key? method, a corresponding message is printed using the puts method.
Comments
Post a Comment