Home » Ruby programming

Hash.invert Method with Example in Ruby

Ruby Hash.invert Method: Here, we are going to learn about the Hash.invert Method with examples in Ruby programming language.
Submitted by Hrithik Chandra Prasad, on March 12, 2020

Hash.invert Method

In this article, we will study about Hash.invert Method. The working of this method can be predicted with the help of its name but it is not as simple as it seems. Well, we will understand this method with the help of its syntax and program code in the rest of the content.

Method description:

This method is a public instance method that is defined in Ruby library especially for Hash class. This method works in a way that it creates a new hash object in which the keys of the self hash are values and values of the self hash are keys. If a key with the same values already exists in the hash object then the last key will be utilized and the previous one will be discarded. This method is one of the examples of non-destructive methods, where the changes created by the method are temporary.

Syntax:

    Hash_object.invert

Argument(s) required:

This method does not require any argument.

Example 1:

=begin
  Ruby program to demonstrate invert method
=end	

hash1={"color"=>"Black","object"=>"car","love"=>"friends","fruit"=>"Kiwi","vege"=>"potato"}

puts "Hash.invert implementation"
ary = hash1.invert

puts "Hash object after inverting: #{ary}"

puts "Self hash object : #{hash1}"

Output

Hash.invert implementation
Hash object after inverting: {"Black"=>"color", "car"=>"object", "friends"=>"love", "Kiwi"=>"fruit", "potato"=>"vege"}
Self hash object : {"color"=>"Black", "object"=>"car", "love"=>"friends", "fruit"=>"Kiwi", "vege"=>"potato"}

Explanation:

In the above code, you can observe that we are inverting the hash object with the help of the Hash.invert method. In the new hash, the keys are values and values are keys. You can see that this method is not creating any impact upon the actual hash because this method is one of the examples of non-destructive methods.

Example 2:

=begin
  Ruby program to demonstrate invert method
=end	

hash1={"color"=>"Black","object"=>"car","love"=>"friends","fruit"=>"Kiwi","vege"=>"potato"}

puts "Hash.invert implementation"
ary = hash1.invert.invert

puts "Hash object after inverting: #{ary}"

puts "Self hash object : #{hash1}"

Output

Hash.invert implementation
Hash object after inverting: {"color"=>"Black", "object"=>"car", "love"=>"friends", "fruit"=>"Kiwi", "vege"=>"potato"}
Self hash object : {"color"=>"Black", "object"=>"car", "love"=>"friends", "fruit"=>"Kiwi", "vege"=>"potato"}

Explanation:

In the above code, you can observe that we can invert a hash object with the help of the Hash.invert method. You can even see that we can do cascading of methods and we are getting the same hash after invoking invert twice.




Comments and Discussions!

Load comments ↻






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