Ruby | Enumerator each function

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 initialised object.

Parameters: This function accepts constituent of the initialised object as the parameter.



Returns: the constituent elements of the initialised object.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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}"

chevron_right


Output:

name = Geek
age = 22
{"name"=>"Geek", "age"=>"22"}

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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}"

chevron_right


Output:

GFG
gfg
Geeks
Geek
["GFG", "gfg", "Geeks", "Geek"]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.