Open In App
Related Articles

Ruby | Enumerator each function

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
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:
# 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:
# 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"]

Last Updated : 27 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads