Home » Ruby programming

Hash > Operator in Ruby

Here, we are going to learn about the Hash > operator in Ruby programming language with examples.
Submitted by Hrithik Chandra Prasad, on February 16, 2020

In the last article, we have seen how we can carry out a comparison between two hash objects with the help of "==" operator? "==" method is a public instance method defined in Ruby’s library.

In this article, we will see the implementation of the ">" operator. The working is pretty clear with the help of its name. It is not as simple as it seems. We will figure it out in the content of this article. We will understand it with the help of syntaxes and demonstrating program codes.

Method description:

This method is a public instance method that is defined in Ruby's library especially for Hash class. This method works in a way that it carries out a comparison between two different hashes and returns a Boolean value. The method returns true when the second hash is a subset of first hash and returns false if it is not the subset of the first Hash instance. Being a subset simply means to have all those elements which are present in another Hash object.

Syntax:

    Hash > Hash_object -> true or false

Parameter(s) required:

This method does not require any argument.

Example 1:

=begin
  Ruby program to demonstrate > operator
=end	

hash1={"color"=>"Black","object"=>"phone","love"=>"mom","fruit"=>"Kiwi","vege"=>"potato","place"=>"null"}

hash2= {"color"=> "Black", "object"=>"phone", "love"=>"mom","fruit"=>"Kiwi","vege"=>"potato"}

if(hash1>hash2)
	puts "hash2 is a subset of hash1"
else
	puts "hash2 is not a subset of hash1"
end

Output

hash2 is a subset of hash1

Explanation:

In the above code, you can simply observe that the method has returned true inside the if condition that is because the message is printed as "hash2 is the subset of  hash1". This happened because hash2 has all the elements which are present in hash1. This is the simple meaning of subset.

Example 2:

=begin
  Ruby program to demonstrate > operator
=end	

hash1= {"color"=> "Black", "object"=>"phone", "love"=>"mom","fruit"=>"Kiwi","vege"=>"potato"}

hash2={"color"=>"Black","object"=>"phone","love"=>"mom","fruit"=>"Kiwi","vege"=>"potato","place"=>"null"}

if(hash1>hash2)
	puts "hash2 is a subset of hash1"
else
	puts "hash2 is not a subset of hash1"
end

Output

hash2 is not a subset of hash1

Explanation:

In the above code, you can simply observe that the method has returned false inside the if condition that is because the message is printed as "hash2 is not a subset of hash1". This happened because hash2 is not having all the elements which are present in hash1. This is the simple meaning of subset.



Comments and Discussions!

Load comments ↻





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