Dissecting and Demystifying: Reduce/Inject
Reduce (a.k.a. Inject) is an enumerable method that recently made a whole lot of sense to me, so I figured that it was time to do a deep dive into how reduce
works and what it can do for us using Blocks and Symbols.
Block
reduce
takes three arguments: a collection, an initial value, and a function. If an initial value isn’t given then it defaults to the first value in the collection.
In add_numbers
the arguments are as follows:
Collection: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Initial Value: 0
Function: Add each element from the collection to the initial value and return a total.
reduce
initializes the variable “sum” with the value of 0 and keeps a running total of each return value. In other words, a number from the collection is added each time to the initial value and the total sum becomes the new sum for the next value waiting to be added.
Let’s see what this example looks like using each
instead:
reduce
is like an each
with superpowers!
Our initial value can also be an array or a hash.
Symbol
reduce
also accepts a symbol, which makes addition and multiplication very easy and simple to read.
The :
tells Ruby that we are going to give it a symbol, which in our case is a +
(this is the name of the addition method, you can also give it a *
for the multiplication method). By passing in a symbol we can apply a method to each one of the values in the collection.
The operator methods can be broken down as follows: