Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Ruby | Enumerator each function

  • Last Updated : 27 Oct, 2021

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"]
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!