×

Ruby Tutorial

Ruby Basics

Ruby Control Statements

Ruby Methods

Ruby Classes and Methods

Ruby Arrays

Ruby Sets

Ruby Strings

Ruby Classes & Objects

Ruby Hash

Ruby Tools

Ruby Functions

Ruby Built-in Functions

Misc.

Ruby Programs

Ruby Hash.has_key?() Method

By IncludeHelp Last updated : December 01, 2024

In this article, we will study about Hash.has_key?() Method. The working of the method can't be assumed because it's quite a different name. Let us read its definition and understand its implementation with the help of syntax and program codes.

Description and Usage

This method is a Public instance method and belongs to the Hash class which lives inside the library of Ruby language. Hash.has_key?() method is used to check whether a key(key-value) is a part of the particular Hash instance or not and that Hash instance should be a normal Hash instance. It will search through the whole Hash and gives you the result according to its search. Let us go through the syntax and demonstrating the program codes of this method.

If you are thinking, what it will return then let me tell you, it will return a Boolean value. The returned value will be true if it finds the key inside the Hash and the return value will be false if it does not find the key to be the part of Hash instance.

Syntax

Hash_instance.has_key?(obj)

Parameters

This method only takes one parameter and that argument is nothing but the key whose presence we want to check.

Example 1

=begin
  Ruby program to demonstrate Hash.has_key method
=end	

hsh = {"colors"  => "red",
  "letters" => "a", "Fruit" => "Grapes"}

puts "Hash.has_key implementation:"

puts "Enter the Key you want to search:"
ky = gets.chomp

if (hsh.has_key?(ky))
	puts "Key found successfully"
else
	puts "Key not found!"
end

Output

Hash.has_key implementation:
Enter the Key you want to search:
 colors
Key found successfully

Explanation

In the above code, you can observe that we are invoking the Hash.has_key() method on the normal Hash instance. It has returned true when it found the presence of the key in the Hash object which is entered by the user.

Example 2

=begin
  Ruby program to demonstrate Hash.has_key method
=end	

hsh = {"colors"  => "red",
  "letters" => "a", "Fruit" => "Grapes"}

hsh1 = {"cars"  => "800",
  "bike" => "pulsar", "phone" => "A50"}

hsh2 = {"one"=> hsh, "two" => hsh1}

puts "Hash.has_key implementation:"

puts "Enter the Key you want to search:"
ky = gets.chomp

if (hsh2.has_key?(ky))
	puts "Key found successfully"
else
	puts "Key not found!"
end

Output

Hash.has_key implementation:
Enter the Key you want to search:
 cars
Key not found!

Explanation

In the above, you can verify that Hash.has_key?() the method does not work upon Hash instance which is the collection of multiple Hash instances. It will return false even if the object is a part of the Hash instance.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.