| dict |
dict := #{'foo'->'brown'. 'bar'->'yellow'.
'qix'->'white'. 'baz'->'red'. 'flub'->'green'} asDictionary.
dict at: 'qix'
If I PrintIt
, I get 'white'. If I remove 'asDictionary', I still get 'white'. What does a dictionary give me that a collection of associations doesn't?
Expression like #{exp1 . sxp2 . exp3}
is amber-smalltalkspecific and creates a HashedCollection, which is a special kind of dictionary where keys are strings (probably in Javascript you use things like this a lot).
In other smalltalks there is no expression like that. Instead array expressions which look like: {exp1 . sxp2 . exp3}
(there is no leading #
) were introduced in squeak and are also available in pharo (which is a fork of Squeak) and Amber. Now the array expression creates an Array and so you have to use integers for #at:
message. For example dict at: 2
will return you an association 'bar'->'yellow'
because it is on the second position of the array you've created.
#asDictionary
is a method of a collection that converts it into a dictionary given that the elements of the collection are associations. So if you want to create a dictionary with keys other than strings, you can do it like this:
dict := {
'foo' -> 'brown' .
1 -> 'yellow' .
3 @ 4 -> 'white' .
#(1 2) -> 'red' } asDictionary
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With