Maps in Crystal
Maps are Crystal’s built-in associative data type (sometimes called hashes or dicts in other languages).
To create an empty map, use the built-in Hash
class:
Set key/value pairs using typical name[key] = val
syntax.
Printing a map with e.g. puts
will show all of its key/value pairs.
Get a value for a key with name[key]
.
If the key doesn’t exist, nil
is returned.
The built-in size
returns the number of key/value pairs when called on a map.
The built-in delete
removes key/value pairs from a map.
To remove all key/value pairs from a map, use the clear
method.
The optional second return value when getting a value from a map indicates if the key was present in the map. This can be used to disambiguate between missing keys and keys with zero values like 0
or ""
. Here we didn’t need the value itself, so we ignored it with the blank identifier _
.
You can also declare and initialize a new map in the same line with this syntax.
Crystal doesn’t have a direct equivalent to the maps
package in the example, but you can compare maps using the equality operator ==
.
Note that maps appear in the form {"k" => "v", "k" => "v"}
when printed with puts
.