![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
One way to add up the elements in an Array
instance is to send the array the do:
message with a block as an
argument. The following shows what the appropriate block looks like, given
that the array is assigned to Calories
, a global variable, and that
sum
, a local variable, is initially assigned to 0:
Calories do: [:element | sum := sum + element].
Observe that blocks sent along with the do:
message have a parameter
reminiscent of the parameter blocks involved in to:do:
messages,
which you learned about in Segment 307. The receiver, an
array, handles such a block by evaluating the block as many times as there
are elements in the array. Each such evaluation is done with a different
array element assigned to the parameter. Thus, do:
expressions
perform computations that center on enumeration.