Ruby | Enumerable each_witth_object() function

The each_with_object() of enumerable is an inbuilt method in Ruby iterates for every object and returns the initial object. It returns the enumerator, if no block is given.

Syntax: enu.each_with_object(obj) { |obj| block }

Parameters: The function takes the block which is used to initialise the initial object.



Return Value: It returns the enumerator, if no block is given, else it returns the initial object.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program for each_with_object method in Enumerable
  
# Initialize 
enu = [7, 9, 10]
  
# Prints each with object
enu.each_with_object([]) { |obj, el| el << obj+10 }

chevron_right


Output:

[17, 19, 20]

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program for each_with_object method in Enumerable
  
# Initialize 
enu = [7, 9, 10]
  
# Prints each with object
enu.each_with_object([])

chevron_right


Output:

Enumerator: [7, 9, 10]:each_with_object([])


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.