You probably frequently have to iterate through a list and accumulate a result that changes as you iterate. Let’s take the following array:
If you want to find a sum of all the items in the array, you could write something like this:
This works fine, but it doesn’t look much elegant. Luckly, for us that wants to be elegant there is a inject method. (See: Enumerable::inject)
This code does the same thing, but also looks cool. Inject acomplish this by using accumulator or accumulated value (x). At each step accumulated value is set to the value returned by the block. Here, we set accumulator initial value to 0, and at each step current value from array (n) is added to accumulated value.
If initial value is omitted, the first item is used as the accumulator initial value and is then omitted from iteration.
Is same as
Another example. We have array with five names:
The following code:
You can get the same output with:
Now, let’s say you won’t to separate them with comma, and capitalize those that have more then four characters. You can do it like this:
Or like this:
In both ways we get the same result: