Home » Ruby programming

Hash.values Method with Example in Ruby

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

Hash.values Method

In this article, we will study about Hash.values 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.

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 returns an array that contains all the values present in the hash object. This method traverses the whole hash object and stores the values inside the array to be returned with a separate index. The Hash.values() method will return an empty array instance if there is no value present inside the hash object.

Syntax:

    Hash_object.values

Argument(s) required:

This method does not take any parameter. It returns a hash which contains all the values of hash object.

Example 1:

=begin
  Ruby program to demonstrate Hash.values method
=end	

hsh = {"colors"  => "red","city"=>"Nainital", "Fruit" => "Grapes", "anything"=>"red","sweet"=>"ladoo"}

puts "Hash.values implementation"

ary = hsh.values

puts "Values present in the hash are:"

ary.each do |val|
	puts val
end

Output

Hash.values implementation
Values present in the hash are:
red
Nainital
Grapes
red
ladoo

Explanation:

In the above code, you can observe that we can get all the values present inside a particular hash object with the help of the Hash.values() method. You can see that all the values are stored inside an array object which can be displayed.

Example 2:

=begin
  Ruby program to demonstrate Hash.values method
=end	

hsh = {"colors" => ["red","blue","green"],"city"=>"Nainital", "Fruit" => "Grapes", "anything"=>"red","sweet"=>"ladoo"}

puts "Hash.values implementation"

ary = hsh.values

puts "Values present in the hash are:"

puts "#{ary}"

Output

Hash.values implementation
Values present in the hash are:
[["red", "blue", "green"], "Nainital", "Grapes", "red", "ladoo"]

Explanation:

In the above code, you can observe that you can fetch all the values from a hash object with the help of the Hash.values() method. In the above code, you can observe that a multidimensional array object has been returned because the hash object was containing an array of values stored inside a particular key.



Comments and Discussions!

Load comments ↻





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