Maps are immutable and keep the order in which keys were added. Keys are Int, String or Bytes.

a == b is true when the two maps have the same keys with equal values, in any order; the value type must have equality (not Fn, Task, Channel, a handle or JSON.Value).

size and empty? #

Map.size(map: Map[K, V]) -> Int
Map.empty?(map: Map[K, V]) -> Bool
def main() -> Void
  puts({"a": 1, "b": 2}.size)
  puts({"a": 1, "b": 2}.empty?)
end
Output
2
false

size is O(1): the map keeps its count.

get #

Map.get(map: Map[K, V], key: K) -> Optional[V]
Map.get(map: Map[K, V], key: K, default: V) -> V

With two arguments, get gives an Optional: some(value), or none when the key is missing. With a third argument, it gives the value or the default; the default is always evaluated, and false and nil are present values.

def main() -> Void
  ages = {"Ana": 25}
  puts(ages.get("Ana"))
  puts(ages.get("Bob").none?)
  puts(ages.get("Bob", 0))
  case ages.get("Ana")
    some(age) -> puts("Ana is #{age}")
    none -> puts("no Ana")
  end
end
Output
some(25)
true
0
Ana is 25

map[key] also reads a value, and stops the program when the key is missing.

has_key? and key? #

Map.has_key?(map: Map[K, V], key: K) -> Bool

m.key?(k) is the Ruby name of Map.has_key?.

def main() -> Void
  m = {1: "one"}
  puts(m.key?(1))
  puts(m.key?(2))
end
Output
true
false

put #

Map.put(map: Map[K, V], key: K, value: V) -> Map[K, V]

Adds or replaces an entry. A replaced key keeps its place.

def main() -> Void
  m = {"a": 1, "b": 2}
  puts(m.put("c", 3))
  puts(m.put("a", 10))
end
Output
{"a": 1, "b": 2, "c": 3}
{"a": 10, "b": 2}

delete #

Map.delete(map: Map[K, V], key: K) -> Map[K, V]

Removes a key and keeps the order of the rest. A missing key is fine, and a key put back later goes to the end. It is O(log32 n) amortized along one line of versions, with an O(n) rebuild of the key list after many deletes.

def main() -> Void
  m = {"a": 1, "b": 2}
  puts(m.delete("a"))
  puts(m.delete("zzz"))
end
Output
{"b": 2}
{"a": 1, "b": 2}

keys and values #

Map.keys(map: Map[K, V]) -> List[K]
Map.values(map: Map[K, V]) -> List[V]

Both follow insertion order.

def main() -> Void
  m = {"x": 1, "y": 2}
  puts(m.keys)
  puts(m.values)
end
Output
["x", "y"]
[1, 2]

each #

Map.each(map: Map[K, V], block: Fn[K, V, Void]) -> Void

Runs the function with each key and value, in insertion order.

def main() -> Void
  {"x": 1, "y": 2}.each do |key, value| puts("#{key}=#{value}") end
end
Output
x=1
y=2

filter and select #

Map.filter(map: Map[K, V], block: Fn[K, V, Bool]) -> Map[K, V]

Keeps the entries for which the function gives true, in insertion order. O(n), like each. m.select is the Ruby name.

def main() -> Void
  stock = {"apple": 3, "fig": 0, "kiwi": 7}
  puts(stock.select do |_, count| count > 0 end)
end
Output
{"apple": 3, "kiwi": 7}