Dictionary in Smalltalk
Keys to values, with at:ifAbsent: reading safely.
"Dictionary maps keys to values; at:ifAbsent: reads safely."
| prices |
prices := Dictionary new.
prices at: 'broadside' put: 120.
prices at: 'chapbook' put: 340.
prices at: 'bookmark' put: 15.
Transcript show: (prices at: 'chapbook') printString; cr.
Transcript show: (prices at: 'poster' ifAbsent: [0]) printString; cr.
prices keysAndValuesDo: [:job :cents |
Transcript show: job, ' -> ', cents printString; cr].
Transcript show: prices keys asSortedCollection printString; cr.
How it works
at:put:writes;at:reads and raises on a miss.at:ifAbsent:supplies a block for the missing case.keysAndValuesDo:walks both halves at once.
Keywords and builtins used here
DictionaryTranscriptasSortedCollectioncrkeysnewprintString
The run, in numbers
- Lines
- 14
- Characters to type
- 482
- Tokens
- 82
- Three-star pace
- 60 tpm
At the three-star pace of 60 tokens a minute, this run takes about 82 seconds.
Step 2 of 4 in Collections, step 11 of 31 in Language basics.