Blocks
Blocks are groups of expressions delimited by square brackets ([ ]). They are used for conditional testing and loops, and as arguments to scripts. Blocks can be nested inside other blocks.
Conditional testing
To test for conditions in scripts, send the messages ifTrue: and ifFalse: to a Boolean object. The messages ifTrue: and ifFalse: each take a block as an argument.
This example answers true:
| aNumber |
aNumber := 500.
(aNumber > 100) ifTrue: [^true].
This example answers false:
| aString |
aString := 'def'.
(aString = 'abc') ifTrue: [^true]
ifFalse: [^false].
Loops
The following script shows how to write a simple do-loop using blocks:
1 to: 10 do: [:i | Transcript show: i printString; cr.].
Notice the syntax :i |. This is how block arguments are declared inside blocks. The block argument is used only inside the block.
To display strings in the System Transcript send the show: message to the Transcript object. Note the cascaded cr message. This is an abbreviation for carriage return and causes the cursor to move to the start of the next line in the System Transcript.
You can also iterate through the members of a collection using blocks. The following example adds the word 'a' in front of each member of a collection:
| aCollection |
aCollection := OrderedCollection new.
aCollection add: 'Brachiosaur';
add: 'Pterodactyl';
add: 'Velociraptor'.
aCollection do: [:each |Transcript show: 'a ', each; cr.].
Finally, here's a simple while-loop:
| i |
i := 10.
[i > 0] whileTrue: [Transcript show: i printString; cr.
i := i - 1.].
Last modified date: 01/29/2015