Open In App

Ruby | Enumerator each function

Last Updated : 27 Oct, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report
The Enumerator#each function in Ruby is used to Iterates over the object according to how this Enumerator was constructed and returns the object's values.
Syntax: A.each { |key, value| print key + ' = ' + value + "\n" } Here, A is the initialized object. Parameters: This function accepts constituent of the initialized object as the parameter. Returns: the constituent elements of the initialized object.
Example 1: Ruby
# Initialising a Hash object
name_age = { 'name' => 'Geek', 'age' => '22' }

# Calling the each function
C = name_age.each { |key, value| print key + ' = ' + value + "\n" }

# Getting the key and value of hash object
puts "#{C}"
Output:
name = Geek
age = 22
{"name"=>"Geek", "age"=>"22"}
Example 2: Ruby
# Initialising a array
stooges = ['GFG', 'gfg', 'Geeks', 'Geek'] 

# Calling the each function
C = stooges.each { |stooge| print stooge + "\n" } 

# Getting the values of the array
puts "#{C}"
Output:
GFG
gfg
Geeks
Geek
["GFG", "gfg", "Geeks", "Geek"]

Next Article

Similar Reads