Ruby has an Enumerable method called inject and it makes summing or getting the product of an array of values a snap. Below are some extended examples of it in use:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
So what does inject do?
- The first argument of the block takes the value of the variable passed to inject (the injected variable) initially
- After performing the block’s operation the result is stored in that same variable and at the end that final stored value is returned
- If you don’t pass in a value to inject, the first argument of the block will initially take on the value of the first index in the array.
Read some more here: http://ruby-doc.org/core-2.1.3/Enumerable.html#method-i-inject
It can be made even shorter
1 2 3 4 |
|
The first argument is the injection, the second is calling on the symbol for the operator +. Symbol references to methods are also acceptable arguments for inject.
Summary
Instead of
1 2 |
|
You can do this:
1
|
|