Home »
Ruby Tutorial
Ruby Hash.values_at() Method
By IncludeHelp Last updated : December 01, 2024
In this article, we will study about Hash.values_at() Method. The working of the method can be assumed because of its very common name but there exist some hidden complexities too. Let us read its definition and understand its implementation with the help of syntax and program codes.
Description and Usage
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 returns an array that contains all the values of the keys which are passed along with the method at the time of its invocation. This method traverses the whole hash object and finds the particular value of the keys which are specified. The Hash.values_at() method will return an empty array instance if keys given with the method are not present inside the hash object.
Syntax
Hash_object.values_at(keys, ...)
Parameters
This method can accept any number of arguments. These arguments are nothing but the keys whose values you want to find.
Example 1
=begin
Ruby program to demonstrate Hash.values_at method
=end
hsh = {"colors" => "red","city"=>"Nainital", "Fruit" => "Grapes", "anything"=>"red","sweet"=>"ladoo"}
puts "Hash.values_at implementation"
puts "Enter the first key:"
ky1 = gets.chomp
puts "Enter the second key:"
ky2 = gets.chomp
puts "Enter the third key:"
ky3 = gets.chomp
ary = hsh.values_at(ky1,ky2,ky3)
puts "values present in the array are:"
ary.each do |key|
puts key
end
Output
Hash.values_at implementation
Enter the first key:
colors
Enter the second key:
city
Enter the third key:
Fruit
values present in the array are:
red
Nainital
Grapes
Explanation
In the above code, you can observe that we can try to fetch the values with the help of the Hash.values_at() method. You can see that the array returned by the method is having all the values of the keys which are passed with the method.
Example 2
=begin
Ruby program to demonstrate Hash.values_at method
=end
hsh = {"colors" => "red","city"=>"Nainital", "Fruit" => "Grapes", "anything"=>"red","sweet"=>"ladoo"}
puts "Hash.values_at implementation"
ary = hsh.values_at("life","bike")
puts "values present in the array are:"
ary.each do |key|
puts key
end
Output
Hash.values_at implementation
values present in the array are:
Explanation
In the above code, you can observe that we are trying to fetch values from the hash object with the help of the Hash.values_at() method. You can see that when the keys passed by the user are not present in the hash, the method is returning an empty array instance.