Blocks in Smalltalk
Code in brackets, a value until sent value.
"A block is code in brackets, a value until sent value."
| inkCost quote |
inkCost := [:pages | pages * 3].
Transcript show: (inkCost value: 16) printString, ' ml of ink'; cr.
"Blocks close over their surroundings."
quote := 'set solid'.
[Transcript show: 'The foreman says: ', quote; cr] value.
"Zero, one, and two-argument blocks."
[Transcript show: 'wash the rollers'; cr] value.
[:a :b | Transcript show: (a max: b) printString; cr]
value: 12 value: 18.
How it works
[:pages | pages * 3]is a one-argument block.- Blocks close over surrounding temporaries.
value,value:, andvalue:value:run them by arity.
Keywords and builtins used here
TranscriptcrprintStringvalue
The run, in numbers
- Lines
- 13
- Characters to type
- 459
- Tokens
- 76
- Three-star pace
- 60 tpm
At the three-star pace of 60 tokens a minute, this run takes about 76 seconds.
Step 2 of 3 in Messages & blocks, step 5 of 31 in Language basics.