Home »
Ruby programming
Hash.key?(value) Method with Example in Ruby
Ruby Hash.key?(value) Method: Here, we are going to learn about the Hash.key?(value) Method with examples in Ruby programming language.
Submitted by Hrithik Chandra Prasad, on March 12, 2020
Hash.key?(value) Method
In this article, we will study about Hash.key?(value) 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.
Method description:
This method is a Public instance method and belongs to the Hash class which lives inside the library of Ruby language. This method works in a way that it checks the presence of a particular value in the hash object and returns it's key if the value is present in the hash. This value will return nil if it doesn't find the presence of value which is asked by the user which is passed with the method at the time of its invocation.
Syntax:
Hash.key(value)
Argument(s) required:
This method only requires one argument and that value is nothing but the value of the key you want to get.
Example 1:
=begin
Ruby program to demonstrate Hash.key(value) method
=end
hsh = {"colors" => "red","letters" => "a", "Fruit" => "Grapes"}
puts "Hash.key(value) implementation:"
puts "Enter the value you want to search:"
value = gets.chomp
if (hsh.key(value))
puts "Value found successfully key is #{hsh.key(value)}"
else
puts "Key not found!"
end
Output
Hash.key(value) implementation:
Enter the value you want to search:
red
Value found successfully key is colors
Explanation:
In the above code, you can observe that we are finding keys with the help of values by using Hash.key(value) method. You can see that we are asking the user for value whose key he/she wants to find. First, we are checking whether the value is present in the hash or not. If it is not present in the hash object then the method will return 'nil' and you will not get anything as the result.
Example 2:
=begin
Ruby program to demonstrate Hash.key(value) method
=end
hsh = {"colors" => "red","letters" => "a", "Fruit" => "Grapes", "anything"=>"red"}
puts "Hash.key(value) implementation:"
puts "Enter the value you want to search:"
value = gets.chomp
if (hsh.key(value))
puts "Value found successfully key is #{hsh.key(value)}"
else
puts "Key not found!"
end
Output
Hash.key(value) implementation:
Enter the value you want to search:
red
Value found successfully key is colors
Explanation:
With the help of the above code, it is demonstrated that when there are two keys present in the hash object with the same value then instead of returning both the keys, this method returns only first key in which it has found the presence of value.