Map
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]) -> Booldef main() -> Void
puts({"a": 1, "b": 2}.size)
puts({"a": 1, "b": 2}.empty?)
end2
falsesize 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) -> VWith 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
endsome(25)
true
0
Ana is 25map[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) -> Boolm.key?(k) is the Ruby name of Map.has_key?.
def main() -> Void
m = {1: "one"}
puts(m.key?(1))
puts(m.key?(2))
endtrue
falseput #
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{"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{"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["x", "y"]
[1, 2]each #
Map.each(map: Map[K, V], block: Fn[K, V, Void]) -> VoidRuns 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
endx=1
y=2filter 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{"apple": 3, "kiwi": 7}