s LearnSqueak.com

ABSOLUTE BEGINNER

Number the items in a list

Use withIndexDo: to get an item and its position together. Make a tiny numbered menu in five steps.

5 minutes · 5 small steps · Squeak 6.1

STEP 1

Make a list

A list keeps its items in order. This one has three drink names.

Select the whole expression, then Print it
#('Tea' 'Milk' 'Water')
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Make a list gives #('Tea' 'Milk' 'Water')
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

Tea appears first.

STEP 2

Get the first item

Squeak starts counting list positions at 1.

Select the whole expression, then Print it
#('Tea' 'Milk' 'Water') at: 1
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Get the first item gives 'Tea'
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

Change 1 to 2 to see Milk.

STEP 3

See an item beside its number

withIndexDo: runs the words inside the square brackets once for each item. The item comes first and the position comes second.

Select the whole expression, then Print it
| rows |
rows := OrderedCollection new.
#('Tea' 'Milk' 'Water') withIndexDo: [:drink :number |
  rows add: {drink. number}].
rows asArray
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: See an item beside its number gives #(#('Tea' 1) #('Milk' 2) #('Water' 3))
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

Milk is paired with 2.

STEP 4

Make a numbered menu

printString turns each number into text. A comma joins it to the dot, space and drink name.

Select the whole expression, then Print it
| menu |
menu := OrderedCollection new.
#('Tea' 'Milk' 'Water') withIndexDo: [:drink :number |
  menu add: number printString, '. ', drink].
menu asArray
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Make a numbered menu gives #('1. Tea' '2. Milk' '3. Water')
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

You now have one numbered label per drink.

STEP 5

Number a different list

The same block works on any list of names. Each new list starts at 1.

Select the whole expression, then Print it
| menu |
menu := OrderedCollection new.
#('Mango' 'Guava') withIndexDo: [:fruit :number |
  menu add: number printString, '. ', fruit].
menu asArray
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Number a different list gives #('1. Mango' '2. Guava')
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

Add an item and predict its number before printing.

YOU DID IT

A small step. A real result.

withIndexDo: gives the block the item first and its one-based position second.

Optional code download: open it as text and copy one example into Workspace.

Download the five examples; copy one at a time

Make your first list · Transform every item