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:

# Create an empty map
m = Hash.new

Set key/value pairs using typical map[key] = value syntax.

# Set key/value pairs
m["k1"] = 7
m["k2"] = 13

Printing a map with puts will show all of its key/value pairs.

# Print the map
puts "map: #{m}"

Get a value for a key with map[key].

# Get a value for a key
v1 = m["k1"]
puts "v1: #{v1}"

If the key doesn’t exist, nil is returned.

# Attempt to get a value for a non-existent key
v3 = m["k3"]
puts "v3: #{v3}"

The size method returns the number of key/value pairs in the map.

# Get the size of the map
puts "len: #{m.size}"

The delete method removes key/value pairs from the map.

# Delete a key/value pair
m.delete("k2")
puts "map: #{m}"

To remove all key/value pairs from a map, use the clear method.

# Clear all key/value pairs
m.clear
puts "map: #{m}"

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 _.

# Check presence of a key using hash's key? which returns a boolean value
prs = m.key?("k2")
puts "prs: #{prs}"

You can also declare and initialize a new map in the same line with this syntax.

# Declare and initialize a new map
n = { "foo" => 1, "bar" => 2 }
puts "map: #{n}"

The == method can be used to compare two maps for equality.

# Compare two maps
n2 = { "foo" => 1, "bar" => 2 }
if n == n2
  puts "n == n2"
end

When you run this Ruby code, you will see the following output:

map: {"k1"=>7, "k2"=>13}
v1: 7
v3: 
len: 2
map: {"k1"=>7}
map: {}
prs: false
map: {"foo"=>1, "bar"=>2}
n == n2

Next example: Functions.