Home »
Ruby »
Ruby Programs
Ruby program to search an item in the hash collection
Ruby Example: Write a program to search an item in the hash collection.
Submitted by Nidhi, on February 18, 2022
Problem Solution:
In this program, we will create a hash collection then we will search an item into the hash collection using value?() method.
Program/Source Code:
The source code to search an item in the hash collection is given below. The given program is compiled and executed on Windows 10 Operating System successfully.
# Ruby program to search an item
# in hash collection
hash = {"101" => "Arun", "102" => "Sumit", "103" => "Mukesh"};
print "Enter item: ";
item = gets.chomp;
if hash.value?(item)==true
printf "The item '%s' found in hash collection",item;
else
printf "Item %s not found",item;
end
Output:
Enter item: Sumit
The item 'Sumit' found in hash collection
Explanation:
In the above program, we created a hash collection to store student information. Then we used value?() method to search an item into the hash collection. The value?() method returns true if ITEM is found in the hash collection, otherwise, it returns a false and printed appropriate message.
Ruby Hashes Programs »