I\'m trying to figure out how each_with_object is supposed to be used.
I have a sum example that doesn\'t work:
> (1..3).each_with_ob
A simple, but common example using each_with_object is when you need to build a hash depending on elements in an array. Very often you see something like:
hash = {}
[1, 2, 3, 4].each { |number| hash[number] = number**2 }
hash
Using each_with_object avoids the explicit initialization and return of the hash variable.
[1,2,3,4].each_with_object({}) { |number, hash| hash[number] = number**2 }
I advise reading the docs for inject, tap and each_with_index. These methods are helpful when you aim for short and readable code.