- list.inject(0) { sum, item | sum + item }
- Apply the closure to each element of the list, passing in the element and
the result of running the closure on the previous element. The value of
inject is the result of the final application of the closure. The argument
to inject is the initial value used with the first element.
- In the above, think of it as injecting a + operation
inbetween each element of a list
- Here’s a definition of factorial using inject
def factorial(n) {
(2..n).inject(1) { fact, i | fact * i }
}