Arrays
Initializing Arrays
You can initialize arrays in Crystal as such:
friends = [] of String
peers = Array(String).new
Note that you cannot use initialize empty array with the following syntax:
friends = [] # => Error: for empty arrays use [] of ElementType
We can however use the following syntax to create an array whose type will be inferred by the compiler:
friends = ["John", "Edward", "Ariel"]
p typeof(friends) # => Array(String)
peers = %w(Bill Marucio)
p typeof(peers) # => Array(String)
It's also possible to create Arrays of a union type. See what the compiler infers:
items = ["John", 'C', 42]
p typeof(items) # => Array(Char|Int32|String)
When union types are used, the compiler will check if all the methods that are called on these types exist or not.
Adding Items
Let's add some items of the String type to the arrays:
friends << "Jane"
peers << "Brian"
You cannot add another type to an array of strings:
friends << "42" # => Error
Accessing Items
You can access elements via indexing. You can also use ranges:
friends = ["John", "Edward", "Ariel", "Alex", "Chael"]
p friends[0] # => "John"
# A sub-array using ranges:
p friends[1, 3] # => ["Edward", "Ariel", "Alex"]
p friends[1..3] # => ["Edward", "Ariel", "Alex"] (1 to 3, 3 inclusive)
p friends[1...3] # => ["Edward", "Ariel"] (1 to 3, 3 exclusive)
It's a good idea to check if a certain index is within bounds, otherwise
you can get a runtime error. If you use the []? syntax, you'll get a nil
instead of a runtime error.
friends = ["John", "Edward", "Ariel", "Alex", "Chael"]
p friends[5] # => Exception: Index out of bounds
# Making sure index 5 exists:
p friends[5]? # => nil
Checking if an item exists in array by it's value:
friends = ["John", "Edward", "Ariel", "Alex", "Chael"]
p friends.includes? "John" # => true
p friends.includes? "Bob" # => false
Removing items
You can use shift and pop methods to remove items at the
first and the last indices.
friends = ["John", "Edward", "Ariel", "Alex", "Chael"]
p friends.shift # => "John"
p friends.pop # => "Chael"
puts friends # => ["Edward", "Ariel", "Alex"]
You can also use the delete method
friends = ["John", "Edward", "Ariel", "Alex", "Chael"]
friends.delete "John"
puts friends # => ["Edward", "Ariel", "Alex", "Chael"]
Iteration
You can iterate over the elements with the each do block:
friends = ["John", "Edward", "Ariel", "Alex", "Chael"]
friends.each do |i|
puts i
end
Recipes to display contents of array
display = [1, 2, 3, 4, 5, 6, 7, 8, 'A', "hello"]
print display # => [1, 2, 3, 4, 5, 6, 7, 'A', "hello"] (no newline)
puts display # => [1, 2, 3, 4, 5, 6, 7, 'A', "hello"] (with newline)
pp display # => [1, 2, 3, 4, 5, 6, 7, 'A', "hello"] (with newline)
p display.inspect # =>"[1, 2, 3, 4, 5, 6, 7, 8, 'A', \"hello\"]" (with newline)
printf("%s", display[1]) # => 2
p sprintf("%d", display[1]) # => "2"
Other methods
Crystal offers us different ways to manipulate data stored in Arrays, the complete list of these methods are in Crystal API docs.