Ruby | Enumerator each_with_object function

The each_with_object function in Ruby is used to Iterate the given object’s each element.

Syntax: A.each_with_object({})
Here, A is the initialised object.

Parameters: This function does not accept any parameters.



Returns: the new set of values.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Calling the .each_with_object function on an array object
[:gfg, :geeks, :geek].each_with_object({}) do |item, hash|
  
# Converting the array elements into its uppercase
  hash[item] = item.to_s.upcase
end

chevron_right


Output:

{:gfg=>"GFG", :geeks=>"GEEKS", :geek=>"GEEK"}

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Calling the .each_with_object function on a hash
{ foo: 2, bar: 4, jazz: 6 }.each_with_object({}) do 
|(key, value), hash|
  
# Getting the square of the hash's value
  hash[key] = value**2
end

chevron_right


Output:

{:foo=>4, :bar=>16, :jazz=>36}


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.