s LearnSqueak.com

ABSOLUTE BEGINNER

Your First copyWith: in Squeak

Make a new Array with one extra item, without changing the old Array.

5 minutes · 5 small steps · Squeak 6.1

STEP 1

Put the first fruit in a new list

Select the whole line in Workspace and choose Print it. The empty Array gives you a new Array with an apple.

Select the whole expression, then Print it
#() copyWith: 'apple'
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Put the first fruit in a new list gives #('apple')
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

The answer has one item.

STEP 2

Add an item at the end

Pear appears after apple because copyWith: appends the item in the copy.

Select the whole expression, then Print it
#('apple') copyWith: 'pear'
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Add an item at the end gives #('apple' 'pear')
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

Print it to see both fruits.

STEP 3

Keep a repeated item

The copy can include the same item twice. It keeps the original order.

Select the whole expression, then Print it
#('apple' 'pear') copyWith: 'apple'
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Keep a repeated item gives #('apple' 'pear' 'apple')
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

The last item is another apple.

STEP 4

Look at the original Array again

Making a new Array does not edit the old one. We ignored the copy in the third line, so fruit still points to the original.

Select the whole expression, then Print it
| fruit |
fruit := #('apple').
fruit copyWith: 'pear'.
fruit
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Look at the original Array again gives #('apple')
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

The answer is still just apple.

STEP 5

Keep the copy and count its items

Assign the answer back to fruit to keep the new Array. It has two items.

Select the whole expression, then Print it
| fruit |
fruit := #('apple').
fruit := fruit copyWith: 'pear'.
fruit size
NATIVE SQUEAK CAPTURE
Native Squeak Workspace: Keep the copy and count its items gives 2
Native Squeak Workspace showing the code and its actual evaluated result.
You should see

Change the final line to fruit to print the two fruits.

YOU DID IT

A small step. A real result.

copyWith: makes a new Array with the extra item at the end.

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

Download the five examples; copy one at a time

Count matching items · Your first list