Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 37 ยท Collections and Blocks

Arrays and Slices in Crystal

Learn Crystal arrays: typed element types, indexing, push and pop, ranges and slicing, nil-safe access, Slice and StaticArray, with runnable Ruby stand-ins.

An array is the collection you will use most in Crystal. It looks like a Ruby array, but there is one big difference: every Array has a single, known element type that the compiler checks. [1, 2, 3] is an Array(Int32), ["a", "b"] is an Array(String), and a mixed literal becomes an array of a union type. That type knowledge is what makes Crystal fast and safe.

The Crystal compiler is not available on this site. Every Crystal listing here is read-only, and each lesson gives a runnable Ruby stand-in (Ruby runs on our server) that shows the same idea. Ruby has no static types, so where Crystal would reject a program at compile time, the stand-in raises an error at run time instead. The stand-ins are labelled so you always know which is which.

Creating arrays

CRYSTAL
numbers = [1, 2, 3]            # Array(Int32)
names = ["Ada", "Grace"]       # Array(String)
mixed = [1, "two", 3.0]        # Array(Int32 | String | Float64)

empty = [] of Int32            # an empty array needs its type
zeros = Array.new(3, 0)        # [0, 0, 0]
squares = Array.new(4) { |i| i * i }   # [0, 1, 4, 9]
words = %w(red green blue)     # Array(String)

An empty literal [] is an error because the compiler cannot guess the element type; you write [] of Int32 or Array(Int32).new. The typing rule also means that numbers << "x" does not compile: you cannot push a String into an Array(Int32).

Indexing: the nil question

In Ruby, list[10] returns nil when the index is out of range. Crystal separates the two behaviours so the type system can stay honest:

CRYSTAL
list = [10, 20, 30]

list[0]        # 10
list[-1]       # 30, negative indexes count from the end
list[5]        # raises IndexError
list[5]?       # nil, the type is Int32?
list[5]? || 0  # 0
list.fetch(5, 0)   # 0
list.first     # 10, raises if empty
list.first?    # Int32?
list.last?     # Int32?

[] returns Int32 and raises when the index is invalid. []? returns Int32 | Nil, and the compiler then forces you to deal with the nil, for example with if value = list[5]?. This question-mark convention is used across the whole standard library: a method with ? returns nil instead of raising.

Ruby Ruby stand-in: strict index versus nil-safe index

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.

Adding and removing

CRYSTAL
stack = [1, 2]
stack << 3            # push, returns the array
stack.push(4, 5)
stack.pop             # 5
stack.shift           # 1
stack.unshift(0)      # add at the front
stack.insert(2, 99)
stack.delete(99)      # removes by value
stack.delete_at(0)    # removes by position
stack.concat([7, 8])

pop and shift raise on an empty array (pop? and shift? return nil). Methods that end in !, such as sort!, reverse!, map!, uniq! and compact!, change the array in place; the versions without ! return a copy.

Ranges and slicing

A range index returns a new array with a copy of that part. A start and a count work too:

CRYSTAL
a = [10, 20, 30, 40, 50]
a[1..3]      # [20, 30, 40]
a[1...3]     # [20, 30]
a[2..]       # [30, 40, 50]
a[..1]       # [10, 20]
a[1, 2]      # [20, 30]
a[-2..]      # [40, 50]

Beginless and endless ranges (..1, 2..) are very handy for "from here to the end".

Ruby Ruby stand-in: slicing with ranges

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.

Slice and StaticArray

Crystal also has two lower-level buffers. Slice(T) is a fixed-size view of contiguous memory (often bytes read from a file or socket), and StaticArray(T, N) is a fixed-size array stored on the stack:

CRYSTAL
bytes = Bytes.new(4)           # Slice(UInt8), all zero
bytes[0] = 255_u8
sub = bytes[1, 2]              # a view into the same memory, not a copy

point = StaticArray(Int32, 3).new(0)
point[1] = 5

Unlike an array slice produced by a[1..2], a Slice shares memory with the parent, so writes through the sub-slice change the original. Use Array unless you need the exact memory layout.

Useful methods

CRYSTAL
nums = [5, 3, 8, 1]
nums.size           # 4
nums.sort           # [1, 3, 5, 8]
nums.sort { |a, b| b <=> a }
nums.sort_by { |n| -n }
nums.sum            # 17
nums.min            # 1
nums.minmax         # {1, 8}
nums.includes?(8)   # true
nums.index(8)       # 2, Int32?
nums.reverse
nums.uniq
nums.rotate
nums.sample         # random element
nums.shuffle

Note that minmax returns a tuple, not an array. Because the element type is known, nums.sum returns an Int32, and ["a", "b"].sum("") needs the starting value to stay a String.

Ruby Ruby stand-in: a typed array guard

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.

Common mistakes

  • Writing [] without a type. Use [] of String.
  • Expecting a[10] to return nil. Use a[10]?.
  • Relying on a slice copy to change the original. Array range slices copy; Slice views do not.
  • Modifying an array while you iterate over it. Build a new array with map and select instead.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the type of [1, 2, 3] in Crystal?

    Every array has one element type known at compile time; integer literals default to Int32.
  2. 2. How do you get nil instead of an error for an out-of-range index?

    A method name ending in ? returns nil instead of raising, so list[5]? has the type Int32?.
  3. 3. Why does x = [] not compile?

    You must say what the array holds: [] of Int32 or Array(Int32).new.
  4. 4. What happens when you write to a sub-Slice obtained from a Slice?

    A Slice is a view of memory, so a sub-slice shares the same bytes as its parent.

Summary

  • A Crystal Array(T) holds one element type, checked by the compiler.
  • Empty arrays need of Type.
  • [] raises on a bad index, []? returns nil; the same ? rule applies to first?, pop? and more.
  • Range indexes copy; Slice and StaticArray are low-level buffers.
  • Methods ending in ! change the array in place.

Next: Hashes, Named Tuples and Tuples