Ruby program to print the inverted hash collection

Ruby Example: Write a program to print the inverted hash collection.
Submitted by Nidhi, on February 17, 2022

Problem Solution:

In this program, we will create a hash collection. Then we will print the original and inverted hash collection, here we will invert key/value to each other.

Program/Source Code:

The source code to print the inverted hash collection is given below. The given program is compiled and executed on Windows 10 Operating System successfully.

# Ruby program to print the 
# inverted hash collection

student = {"101" => "Amit", "102" => "Arun", "103" => "Sumit"};

print "Original Hash collection: \n",student;
print "\nInverted hash collection: \n",student.invert();

Output:

Original Hash collection: 
{"101"=>"Amit", "102"=>"Arun", "103"=>"Sumit"}
Inverted hash collection: 
{"Amit"=>"101", "Arun"=>"102", "Sumit"=>"103"}

Explanation:

In the above program, we created a hash collection to store student information. Then we printed the inverted hash collection using the invert() method. The invert() method invert the keys and values of created collection from each other.

Ruby Hashes Programs »




Comments and Discussions!

Load comments ↻





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