Ruby | Enumerator each_with_object function
Last Updated :
06 Jan, 2020
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:
[ :gfg , :geeks , :geek ].each_with_object({}) do |item, hash|
hash[item] = item.to_s.upcase
end
|
Output:
{:gfg=>"GFG", :geeks=>"GEEKS", :geek=>"GEEK"}
Example 2:
{ foo: 2 , bar: 4 , jazz: 6 }.each_with_object({}) do
|(key, value), hash|
hash[key] = value** 2
end
|
Output:
{:foo=>4, :bar=>16, :jazz=>36}
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...