×

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.each_value Method

By IncludeHelp Last updated : December 01, 2024

In this article, we will study about Hash.each_value Method. The working of this method can be predicted with the help of its name but it is not as simple as it seems. Well, we will understand this method with the help of its syntax and program code in the rest of the content.

Description and Usage

This method is a public instance method that is defined in Ruby library especially for Hash class. This method works in a way that invokes the block at least once for every individual key present in the hash object. The keys present in the hash object are passed as parameters. This method prints the value of the individual key passed. If you are not providing any block then you should expect an enumerator as the returned value from the each_value method.

Syntax

Hash_object.each_value{|value| block}

Parameters

This method does not accept any arguments. However, you can pass a block along with this method.

Example 1

=begin
  Ruby program to demonstrate each_value method
=end

hsh={"name"=>"Zorawar","class"=>"ukg","school"=>"AASSC","place"=>"Haridwar"}

puts "Hash each_value implementation"

str = hsh.each_value{|value| puts " value :- #{value}"}
puts str

Output

Hash each_value implementation
 value :- Zorawar
 value :- ukg
 value :- AASSC
 value :- Haridwar
{"name"=>"Zorawar", "class"=>"ukg", "school"=>"AASSC", "place"=>"Haridwar"}

Explanation

In the above code, you may observe that we are printing every value from the hash object with the help of the Hash.each_value method. The method is invoking a block, which is taking the value as the argument from the hash object. This method is traversing through the hash object, processing it and giving us the desired output or you can say that letting us know about the value stored in the hash. You can also observe that the method is returning a hash object.

Example 2

=begin
  Ruby program to demonstrate each_value method
=end

hsh={"name"=>"Zorawar","class"=>"ukg","school"=>"AASSC","place"=>"Haridwar"}

puts "Hash each_value implementation"

str = hsh.each_value
puts str

Output

Hash each_value implementation
#<Enumerator:0x00005606681dddb8>

Explanation

In the above code, you can observe that when we are invoking the method without the block then we are getting an enumerator returned from the method.

Comments and Discussions!

Load comments ↻





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