×

Ruby Tutorial

Ruby Basics

Ruby Control Statements

Ruby Methods

Ruby Classes and Methods

Ruby Arrays

Ruby Sets

Ruby Strings

Ruby Classes & Objects

Ruby Hash

Ruby Tools

Ruby Functions

Ruby Built-in Functions

Misc.

Ruby Programs

Ruby Hash.values Method

By IncludeHelp Last updated : December 01, 2024

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.

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 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

Parameters

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.