Maps in Ruby
Maps are built-in associative data types (sometimes called hashes or dicts in other languages).
To create an empty map, use the built-in method Hash.new
:
Set key/value pairs using typical map[key] = value
syntax.
Printing a map with puts
will show all of its key/value pairs.
Get a value for a key with map[key]
.
If the key doesn’t exist, nil
is returned.
The size
method returns the number of key/value pairs in the map.
The delete
method removes key/value pairs from the 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 nil
values. Here we didn’t need the value itself, so we ignored it with _
.
You can also declare and initialize a new map in the same line with this syntax.
The ==
method can be used to compare two maps for equality.
When you run this Ruby code, you will see the following output:
Next example: Functions.