The each_with_object method takes an enumerable collection and iterates through all its elements, building an object as it goes. It returns the object.
This method is shorthand for a common programming idiom:
def get_sum list sum = 0 list.each{|item| sum += item} return sum end
Instead, we can use each_with_object to achieve this in one line:
list.each_with_object(0){|item, sum| sum += item}
For simple examples like this, the inject/reduce methods actually work better, but each_with_object's value is in building more complex objects.
- View the objects used in these examples
- View these examples as a runnable ruby script on GitHub.
Pet Inventory
# list of pet names: inventory.each_with_object([]){|pet, array| array << pet.name} #=> ["dog", "cat", "fish", "scorpion", "beetle", "monkey", "rock"] # hash of pet names/quantities: inventory.each_with_object({}){|pet, hash| hash[pet.name] = pet.quantity} #=> {"dog"=>100, "cat"=>50, "fish"=>1000, "scorpion"=>1, "beetle"=>10000, "monkey"=>2, "rock"=>0}