Arrays in Crystal

Our first example demonstrates the use of arrays in Crystal. In Crystal, an array is a fixed-size list of elements of a specific type.

# Here we create an array `a` that will hold exactly
# 5 integers. The type of elements and size are both
# part of the array's type. By default, an array is
# initialized with zeros.
a = [0, 0, 0, 0, 0]
puts "emp: #{a}"

# We can set a value at an index using the
# array[index] = value syntax, and get a value with
# array[index].
a[4] = 100
puts "set: #{a}"
puts "get: #{a[4]}"

# The `size` method returns the length of an array.
puts "len: #{a.size}"

# Use this syntax to declare and initialize an array
# in one line.
b = [1, 2, 3, 4, 5]
puts "dcl: #{b}"

# Crystal doesn't have a direct equivalent to Go's [...] syntax,
# but you can use Array.new with a block for similar functionality.
c = Array.new(5) { |i| i + 1 }
puts "gen: #{c}"

# In Crystal, you can use the splat operator (*) to specify
# the size of an array and fill the rest with a default value.
d = [100, *Array.new(3, 0), 500]
puts "idx: #{d}"

# Array types in Crystal are one-dimensional, but you can
# compose types to build multi-dimensional data structures.
two_d = Array.new(2) { Array.new(3, 0) }
2.times do |i|
  3.times do |j|
    two_d[i][j] = i + j
  end
end
puts "2d: #{two_d}"

# You can create and initialize multi-dimensional
# arrays at once too.
two_d = [[1, 2, 3], [1, 2, 3]]
puts "2d: #{two_d}"

When you run this program, you’ll see:

emp: [0, 0, 0, 0, 0]
set: [0, 0, 0, 0, 100]
get: 100
len: 5
dcl: [1, 2, 3, 4, 5]
gen: [1, 2, 3, 4, 5]
idx: [100, 0, 0, 0, 500]
2d: [[0, 1, 2], [1, 2, 3]]
2d: [[1, 2, 3], [1, 2, 3]]

Note that arrays in Crystal are printed in the form [v1, v2, v3, ...] when using puts.

Crystal’s arrays are similar to those in many other languages, but with some unique features. They are mutable, can be resized dynamically (unlike in the Go example), and provide many useful methods for manipulation and transformation.