Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 37 ยท Collections and Blocks

Hashes, Tuples and Named Tuples in Crystal

Learn Crystal Hash, Set, Tuple and NamedTuple: typed keys and values, default values, fetch and nil-safe lookup, iteration, destructuring, with Ruby stand-ins.

Crystal has three ways to group values that you will meet constantly: Hash(K, V) for lookups by key, Tuple for a small fixed group of values with different types, and NamedTuple for a fixed group with names. Like arrays, they are all typed, and the compiler tracks the types of every key and every value.

Remember that Crystal code in this lesson is read-only; each idea has a labelled Ruby stand-in that runs on the site.

Hash

CRYSTAL
ages = {"Ada" => 36, "Grace" => 45}      # Hash(String, Int32)
ages["Linus"] = 28
ages["Ada"]            # 36
ages["Zed"]            # raises KeyError
ages["Zed"]?           # nil, type Int32?
ages.fetch("Zed", 0)   # 0
ages.has_key?("Ada")   # true
ages.delete("Grace")   # returns 45
ages.size              # 2

empty = {} of String => Int32

Just as with arrays, [] raises (KeyError) when the key is missing and []? returns nil. An empty hash literal needs the key and value types: {} of String => Int32. Keys can be any type that implements hash and ==: strings, symbols, integers, structs and your own classes.

Default values

A hash can compute a value for missing keys. The block runs when the key is absent, and the usual pattern stores the result:

CRYSTAL
counts = Hash(String, Int32).new(0)           # default value 0
%w(a b a c a).each { |w| counts[w] += 1 }
# {"a" => 3, "b" => 1, "c" => 1}

groups = Hash(Int32, Array(String)).new { |h, k| h[k] = [] of String }
%w(cat dog bird).each { |w| groups[w.size] << w }
# {3 => ["cat", "dog"], 4 => ["bird"]}

Be careful with a shared default: Hash(String, Array(String)).new([] of String) would give every missing key the same array object. Use the block form when the default is mutable.

Ruby Ruby stand-in: counting with a default value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Iterating

CRYSTAL
ages.each { |name, age| puts "#{name} is #{age}" }
ages.each_key { |k| puts k }
ages.each_value { |v| puts v }
ages.each_with_index { |(name, age), i| puts "#{i}: #{name}" }
ages.keys                     # Array(String)
ages.values                   # Array(Int32)
ages.select { |_, age| age > 30 }
ages.map { |name, age| "#{name}:#{age}" }
ages.to_a                     # Array({String, Int32})

A Crystal hash keeps insertion order, just like Ruby. each yields the key and value as two block arguments. Other Enumerable methods yield a tuple {key, value} that you can destructure with parentheses, as in |(name, age), i|.

Set

Set(T) stores unique values and is built on a hash. It lives in the standard library but needs require "set" in older versions (current versions load it for you):

CRYSTAL
seen = Set(String).new
seen << "a"
seen << "a"
seen.size           # 1
seen.includes?("a") # true
Set{1, 2} | Set{2, 3}   # union
Set{1, 2} & Set{2, 3}   # intersection

Tuple

A tuple is an immutable, fixed-size sequence whose elements can have different types. The type is written {Int32, String}, and the compiler remembers the type of each position.

CRYSTAL
pair = {1, "one"}         # Tuple(Int32, String)
pair[0]                   # 1, an Int32
pair[1]                   # "one", a String
pair[2]                   # compile error: index out of range
first, second = pair      # destructuring
a, b = 10, 20
a, b = b, a               # swap

def min_max(list : Array(Int32)) : {Int32, Int32}
  {list.min, list.max}
end

low, high = min_max([4, 9, 1])

Tuples are how Crystal methods return several values. Because the index is a literal, pair[0] is known to be an Int32 and pair[1] a String at compile time, something an array cannot offer.

Ruby Ruby stand-in: returning several values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

NamedTuple

A NamedTuple is a tuple whose positions have names. It is the right tool for a small, short-lived record when a full class would be overkill.

CRYSTAL
point = {x: 3, y: 4}              # NamedTuple(x: Int32, y: Int32)
point[:x]                         # 3
point[:z]                         # compile error: no such key
point[:z]?                        # nil, but only for keys not known at compile time
x, y = point[:x], point[:y]

user = {name: "Ada", age: 36}     # NamedTuple(name: String, age: Int32)
user.each { |key, value| puts "#{key}=#{value}" }

def distance(p : NamedTuple(x: Int32, y: Int32))
  Math.sqrt(p[:x] ** 2 + p[:y] ** 2)
end
distance({x: 3, y: 4})            # 5.0

Keys are symbols that are checked at compile time. Named tuples are immutable, but they are values: copying one is cheap. They also pair well with ** double-splat arguments (greet(**user) calls greet(name: "Ada", age: 36)). If you need mutation, behavior or inheritance, write a class or a struct (covered in the Classes and Modules chapter).

Ruby Ruby stand-in: a named record

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Which one to choose

flowchart TD
  A["I have several values"] --> B{"Same type, any count?"}
  B -->|yes| C["Array(T)"]
  B -->|no| D{"Look up by key at run time?"}
  D -->|yes| E["Hash(K, V)"]
  D -->|no| F{"Do the positions need names?"}
  F -->|yes| G["NamedTuple"]
  F -->|no| H["Tuple"]

A quick guide to the four collection shapes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does ages["Zed"] do when the key is missing?

    [] raises KeyError; use []? for nil or fetch(key, default) for a fallback.
  2. 2. Why does Hash(String, Array(String)).new([] of String) cause surprises?

    The default is a single object. Use the block form Hash.new { |h, k| h[k] = [] of String } for mutable defaults.
  3. 3. What is the main advantage of a Tuple over an Array?

    {1, "one"} is a Tuple(Int32, String), so t[0] is an Int32 and t[1] a String.
  4. 4. Which one fits a small immutable record with named fields?

    {name: "Ada", age: 36} is a NamedTuple whose keys are checked at compile time.

Summary

  • Hash(K, V) is typed and ordered; [] raises KeyError, []? gives nil, fetch gives a default.
  • Use Hash.new(0) for counters and the block form for mutable defaults.
  • Tuple is a fixed group of different types, ideal for returning several values.
  • NamedTuple adds compile-time checked names and is immutable.
  • Set(T) stores unique values.

Next: Blocks, Procs and yield