ABSOLUTE BEGINNER
Your First collect: in Squeak
Use collect: to turn each item in a list into a new value without changing the original list.
STEP 1
Try the rule on one number
Start with one number. Multiplying by 2 doubles it. Next you will use the same rule on a whole list.
3 * 2
Squeak prints 6.
STEP 2
Double every number
Read the square brackets as a rule. Each item takes a turn being called n. The part after the vertical bar says how to make that item's result.
#(1 2 3) collect: [:n | n * 2]
The three results are 2, 4, and 6, in the same order as the inputs.
STEP 3
Measure each word
You can collect a different kind of value. This rule asks each word for its length, so words go in and numbers come out.
#('cat' 'rabbit' 'ox') collect: [:word | word size]
Squeak prints #(3 6 2). Try changing 'ox' to 'bear'. The last result becomes 4.
STEP 4
Look at before and after
Save the original and the result with two names. The braces put both lists side by side so you can compare them.
| original doubled |
original := #(2 5).
doubled := original collect: [:n | n * 2].
{original. doubled}
The first list still contains 2 and 5. The second contains 4 and 10.
STEP 5
Collect answers to a question
The rule may give a yes-or-no result. collect: keeps one answer per item. It does not remove any items just because their answer is false.
#(2 5 8) collect: [:n | n even]
2 and 8 give true, and 5 gives false. You still get three results.
YOU DID IT
A small step. A real result.
collect: uses your rule once on every item and gives you a collection of the results.
Optional code download: open it as text and copy one example into Workspace.