![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
Yet another, much more elegant way to add up the
numbers in an array is to use the powerful inject:into:
method,
inherited from the Collection
class, with a two-argument block:
an Array instance inject: initial value into: [:previousResult :nextElement | statements]
Here is what happens when you send a inject:into:
method:
previousResult
, and the first
element in the array is assigned to nextElement
.
previousResult
, and the
second element in the array is assigned to nextElement
.
inject:into:
is the value produced by the
final evaluation of the block.