typestar

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

  1. [:pages | pages * 3] is a one-argument block.
  2. Blocks close over surrounding temporaries.
  3. value, value:, and value:value: run them by arity.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Messages & blocks, step 5 of 31 in Language basics.

← Previous Next →

Blocks in other languages