inject/reduce methods

The inject/reduce methods take an enumerable collection and return an aggregate value. This is similar to each_with_object, but is simpler. Its typical purpose is to "reduce", a list of objects down to one object of the same class. In this use case, no "initial" value needs to be set, unlike each_with_object. However, the syntax of the given block is slightly different. The aggregate object is passed to the block as the first parameter, and the result of the block will become the new aggregate object which is passed to the block for the next item.

Number List

@numbers = [1, 0, 3, 2, 5, 4, 7, 6, 9, 8]

# sum of all the numbers:
@numbers.reduce(:+)  #=> 45

# multiplying all the numbers:
@numbers.reduce{|sum, number| sum * number}  #=> 0

Pet Inventory

# count all the legs in the store:
@inventory.reduce(0){|sum, pet| sum + (pet.legs * pet.quantity)}  #=> 60612

# animal with highest quantity:
@inventory.reduce{|most_pet, pet| most_pet.quantity > pet.quantity ? most_pet : pet}.name  #=> "beetle"

Pokey Things

# number of words in all pokey things:
@pokey_things.reduce(0){|sum, pokey_thing| sum + pokey_thing.split(/\s+/).size}  #=> 9

# pokey thing with the most words:
@pokey_things.reduce{|longest_thing, thing| longest_thing.size > thing.size ? longest_thing : thing}
    #=> "cactus holding poles with knives attached"

Heroku Log File

# total time to serve all requests:
@requests.reduce(0){|sum, request| sum + request.response_time}  #=> 12126

# request with the slowest response time:
@requests.reduce{|slowest_request, request| slowest_request.response_time < request.response_time ? slowest_request : request }.id  #=> 8

Leave a Reply

Your email address will not be published. Required fields are marked *