Login

Your Name:(required)

Your Password:(required)

Join Us

Your Name:(required)

Your Email:(required)

Your Message :

What is Crystal Array and Why Do We Use Them?

Author: Friday

Jun. 30, 2025

104 0 0

Tags: Mechanical Parts & Fabrication Services

Array - The Crystal Programming Language

Array¶

An Array is an ordered and integer-indexed generic collection of elements of a specific type T.

View Details

Arrays are typically created with an array literal denoted by square brackets ([]) and individual elements separated by a comma (,).

Generic Type Argument¶

The array's generic type argument T is inferred from the types of the elements inside the literal. When all elements of the array have the same type, T equals to that. Otherwise it will be a union of all element types.

An explicit type can be specified by immediately following the closing bracket with of and a type. This overwrites the inferred type and can be used for example to create an array that holds only some types initially but can accept other types later.

Empty array literals always need a type specification:

Percent Array Literals¶

Arrays of strings and arrays of symbols can be created with percent array literals:

Array-like Type Literal¶

Crystal supports an additional literal for arrays and array-like types. It consists of the name of the type followed by a list of elements enclosed in curly braces ({}) and individual elements separated by a comma (,).

This literal can be used with any type as long as it has an argless constructor and responds to <<.

For a non-generic type like IO::Memory, this is equivalent to:

For a generic type like Set, the generic type T is inferred from the types of the elements in the same way as with the array literal. The above is equivalent to:

The type arguments can be explicitly specified as part of the type name:

Splat Expansion¶

The splat operator can be used inside array and array-like literals to insert multiple values at once.

The only requirement is that coll's type must include Enumerable. The above is equivalent to:

class Array(T) - The Crystal Programming Language

class Array(T)

  • Array(T)
  • Reference
  • Object

Overview

An Array is an ordered, integer-indexed collection of objects of type T.

Array indexing starts at 0. A negative index is assumed to be relative to the end of the array: -1 indicates the last element, -2 is the next to last element, and so on.

An Array can be created using the usual .new method (several are provided), or with an array literal:

Array(Int32).new  # => []
[1, 2, 3]         # Array(Int32)
[1, "hello", 'x'] # Array(Int32 | String | Char)

See Array literals in the language reference.

An Array can have mixed types, meaning T will be a union of types, but these are determined when the array is created, either by specifying T or by using an array literal. In the latter case, T will be set to the union of the array literal elements' types.

When creating an empty array you must always specify T:

[] of Int32 # same as Array(Int32)
[]          # syntax error

An Array is implemented using an internal buffer of some capacity and is reallocated when elements are pushed to it when more capacity is needed. This is normally known as a dynamic array.

You can use a special array literal syntax with other types too, as long as they define an argless .new method and a << method. Set is one such type:

set = Set{1, 2, 3} # => Set{1, 2, 3}
set.class          # => Set(Int32)

The above is the same as this:

set = Set(typeof(1, 2, 3)).new
set << 1
set << 2
set << 3

Included Modules

  • Comparable(Array(T))
  • Indexable::Mutable(T)

Defined in:

array.cr
json/any.cr
json/to_json.cr
uri/params/to_www_form.cr
yaml/any.cr
yaml/to_yaml.cr

Constructors

  • .additive_identity : self

    Returns the additive identity of this type.

  • .build(capacity : Int, & : Pointer(T) -> ) : self

    Creates a new Array, allocating an internal buffer with the given capacity, and yielding that buffer.

  • .new(size : Int, value : T)

    Creates a new Array of the given size filled with the same value in each position.

  • .new(ctx : YAML::ParseContext, node : YAML::Nodes::Node)
  • .new(initial_capacity : Int)

    Creates a new empty Array backed by a buffer that is initially initial_capacity big.

  • .new(pull : JSON::PullParser)
  • .new

    Creates a new empty Array.

  • .new(ctx : YAML::ParseContext, node : YAML::Nodes::Node, &)
  • .new(size : Int, & : Int32 -> T)

    Creates a new Array of the given size and invokes the given block once for each index of self, assigning the block's value in that index.

  • .new(pull : JSON::PullParser, &)

Class Method Summary

  • .each_product(arrays : Array(Array), reuse = false, &)

    Yields each ordered combination of the elements taken from each of the arrays as Arrays.

    DEPRECATED Use Indexable.each_cartesian(indexables : Indexable(Indexable), reuse = false, &block) instead

  • .each_product(*arrays : Array, reuse = false, &)

    Yields each ordered combination of the elements taken from each of the arrays as Arrays.

    DEPRECATED Use Indexable.each_cartesian(indexables : Indexable(Indexable), reuse = false, &block) instead

  • .from_json(string_or_io, &) : Nil

    Parses a String or IO denoting a JSON array, yielding each of its elements to the given block.

  • .from_yaml(string_or_io : String | IO, &)
  • .product(arrays : Array(Array))

    Returns an Array of all ordered combinations of elements taken from each of the arrays as Arrays.

    DEPRECATED Use Indexable.cartesian_product(indexables : Indexable(Indexable)) instead

  • .product(*arrays : Array)

    Returns an Array of all ordered combinations of elements taken from each of the arrays as Arrays.

    DEPRECATED Use Indexable.cartesian_product(indexables : Indexable(Indexable)) instead

Instance Method Summary

  • #&(other : Array(U)) : Array(T) forall U

    Set intersection: returns a new Array containing elements common to self and other, excluding any duplicates.

  • #*(times : Int) : Array(T)

    Repetition: Returns a new Array built by concatenating times copies of self.

  • #+(other : Array(U)) : Array(T | U) forall U

    Concatenation.

  • #-(other : Array(U)) : Array(T) forall U

    Difference.

  • #<<(value : T) : self

    Append.

  • #<=>(other : Array)

    Combined comparison operator.

  • #==(other : Array) : Bool

    Equality.

  • #==(other : JSON::Any)
  • #==(other : YAML::Any)
  • #==(other) : Bool

    Returns false (other can only be a Value here).

  • #[](start : Int, count : Int) : Array(T)

    Returns count or less (if there aren't enough) elements starting at the given start index.

  • #[](range : Range) : Array(T)

    Returns all elements that are within the given range.

  • #[]=(start : Int, count : Int, values : Array(T))

    Replaces a subrange with the elements of the given array.

  • #[]=(start : Int, count : Int, value : T) : T

    Replaces a subrange with a single value.

  • #[]=(range : Range, values : Array(T))

    Replaces a subrange with the elements of the given array.

  • #[]=(range : Range, value : T)

    Replaces a subrange with a single value.

  • #[]=(values : Array(T), *, index start : Int, count : Int)

    Replaces a subrange with the elements of the given array.

    DEPRECATED Use #[]=(start, count, values) instead

  • #[]=(value : T, *, index start : Int, count : Int)

    Replaces a subrange with a single value.

    DEPRECATED Use #[]=(start, count, value) instead

  • #[]?(start : Int, count : Int) : Array(T) | Nil

    Like #[](Int, Int) but returns nil if the start index is out of range.

  • #[]?(range : Range) : Array(T) | Nil

    Like #[](Range), but returns nil if range.begin is out of range.

  • #|(other : Array(U)) : Array(T | U) forall U

    Set union: returns a new Array by joining self with other, excluding any duplicates, and preserving the order from self.

  • #clear : self

    Removes all elements from self.

  • #clone : Array(T)

    Returns a new Array that has self's elements cloned.

  • #compact

    Returns a copy of self with all nil elements removed.

  • #compact! : self

    Removes all nil elements from self and returns self.

  • #concat(other : Indexable) : self

    Appends the elements of other to self, and returns self.

  • #concat(other : Enumerable) : self

    Appends the elements of other to self, and returns self.

  • #delete(obj) : T | Nil

    Removes all items from self that are equal to obj.

  • #delete_at(start : Int, count : Int) : self

    Removes count elements from self starting at start.

  • #delete_at(index : Int) : T

    Removes the element at index, returning that element.

  • #delete_at(range : Range) : self

    Removes all elements within the given range.

  • #delete_at(*, index start : Int, count : Int) : self

    Removes count elements from self starting at start.

    DEPRECATED Use #delete_at(start, count) instead

  • #dup : Array(T)

    Returns a new Array that has exactly self's elements.

  • #each_repeated_permutation(size : Int = self.size, reuse = false, &) : Nil
  • #fill(start : Int, & : Int32 -> T) : self

    Yields each index of self, starting at start, to the given block and then assigns the block's value in that position.

    DEPRECATED Use #fill(start.., &) instead

  • #fill(*, from start : Int, & : Int32 -> T) : self

    Yields each index of self, starting at start, to the given block and then assigns the block's value in that position.

    You will get efficient and thoughtful service from EBO.

    Additional reading:
    Spring selection | Tokai Spring industries, Inc.

    DEPRECATED Use #fill(start.., &) instead

  • #fill(*, from start : Int, count : Int, & : Int32 -> T) : self

    Yields each index of self, starting at start and just count times, to the given block and then assigns the block's value in that position.

    DEPRECATED Use Indexable::Mutable#fill(start, count, &) instead

  • #fill(value : T, start : Int, count : Int) : self

    Replaces count or less (if there aren't enough) elements starting at the given start index with value.

  • #fill(value : T, start : Int) : self

    Replaces every element in self, starting at start, with the given value.

    DEPRECATED Use #fill(value, start..) instead

  • #fill(value : T, range : Range) : self

    Replaces every element in range with value.

  • #fill(value : T) : self

    Replaces every element in self with the given value.

  • #fill(value : T, *, from start : Int) : self

    Replaces every element in self, starting at start, with the given value.

    DEPRECATED Use #fill(value, start..) instead

  • #fill(value : T, *, from start : Int, count : Int) : self

    Replaces count or less (if there aren't enough) elements starting at the given start index with value.

    DEPRECATED Use #fill(value, start, count) instead

  • #first(n : Int) : Array(T)

    Returns the first n elements of the array.

  • #flatten

    Returns a new Array that is a one-dimensional flattening of self (recursively).

  • #index(object, offset : Int = 0)

    Returns the index of the first appearance of object in self starting from the given offset, or nil if object is not in self.

  • #insert(index : Int, object : T) : self

    Insert object before the element at index and shifting successive elements, if any.

  • #insert_all(index : Int, other : Indexable) : self

    Inserts all of the elements from other before the element at index.

  • #inspect(io : IO) : Nil

    Appends a String representation of this object which includes its class name, its object address and the values of all instance variables.

  • #last(n : Int) : Array(T)

    Returns the last n elements of the array.

  • #map(& : T -> U) : Array(U) forall U

    Optimized version of Enumerable#map.

  • #map_with_index(offset = 0, & : T, Int32 -> _)

    Optimized version of Enumerable#map_with_index.

  • #pop(n : Int) : Array(T)

    Removes the last n values from self, at index size - 1.

  • #pop : T

    Removes the last value from self, at index size - 1.

  • #pop(&)

    Removes the last value from self.

  • #pop? : T | Nil

    Like #pop, but returns nil if self is empty.

  • #pretty_print(pp) : Nil
  • #product(ary : Array(U)) forall U

    Returns an Array of all ordered combinations of elements taken from each of self and ary as Tuples.

    DEPRECATED Use Indexable#cartesian_product(*others : Indexable) instead

  • #product(enumerable : Enumerable, &)

    Yields each ordered combination of the elements taken from each of self and enumerable as a Tuple.

    DEPRECATED Use Indexable#each_cartesian(*others : Indexable, &block) instead

  • #push(value : T) : self

    Append.

  • #push(*values : T) : self

    Append multiple values.

  • #reject!(& : T -> ) : self

    Modifies self, deleting the elements in the collection for which the passed block is truthy.

  • #reject!(pattern) : self

    Modifies self, deleting the elements in the collection for which pattern === element.

  • #remaining_capacity : Int32
  • #repeated_permutations(size : Int = self.size) : Array(Array(T))
  • #replace(other : Array) : self

    Replaces the contents of self with the contents of other.

  • #reverse : Array(T)

    Returns an array with all the elements in the collection reversed.

  • #rotate(n = 1) : Array(T)

    Returns an array with all the elements shifted to the left n times.

  • #rotate!(n : Int = 1) : self

    Shifts all elements of self to the left n times.

  • #select!(& : T -> ) : self

    Modifies self, keeping only the elements in the collection for which the passed block is truthy.

  • #select!(pattern) : self

    Modifies self, keeping only the elements in the collection for which pattern === element.

  • #shift(n : Int) : Array(T)

    Removes the first n values of self, starting at index 0.

  • #shift : T

    Removes the first value of self, at index 0.

  • #shift(&)

    Removes the first value of self, at index 0, or otherwise invokes the given block.

  • #shift? : T | Nil

    Removes the first value of self, at index 0.

  • #shuffle(random : Random = Random::DEFAULT) : Array(T)

    Returns an array with all the elements in the collection randomized using the given random number generator.

  • #size : Int32

    Returns the number of elements in the array.

  • #skip(count : Int) : Array(T)

    Returns an Array with the first count elements removed from the original array.

  • #sort : Array(T)

    Returns a new instance with all elements sorted based on the return value of their comparison method T#<=> (see Comparable#<=>), using a stable sort algorithm.

  • #sort(&block : T, T -> U) : Array(T) forall U

    Returns a new instance with all elements sorted based on the comparator in the given block, using a stable sort algorithm.

  • #sort! : Array(T)

    Sorts all elements in self based on the return value of the comparison method T#<=> (see Comparable#<=>), using a stable sort algorithm.

  • #sort!(&block : T, T -> U) : self forall U

    Sorts all elements in self based on the comparator in the given block, using a stable sort algorithm.

  • #sort_by(&block : T -> _) : Array(T)

    Returns a new instance with all elements sorted by the output value of the block.

  • #sort_by!(&block : T -> _) : Array(T)

    Sorts all elements in self by the output value of the block.

  • #to_a : self

    Returns an Array with all the elements in the collection.

  • #to_json(json : JSON::Builder) : Nil
  • #to_s(io : IO) : Nil

    Prints a nicely readable and concise string representation of this array to io.

  • #to_unsafe : Pointer(T)

    Returns a pointer to the internal buffer where self's elements are stored.

  • #to_yaml(yaml : YAML::Nodes::Builder) : Nil
  • #transpose

    Assumes that self is an array of arrays and transposes the rows and columns.

  • #truncate(start : Int, count : Int) : self

    Removes all elements except the count or less (if there aren't enough) elements starting at the given start index.

  • #truncate(range : Range) : self

    Removes all elements except those within the given range.

  • #uniq : Array(T)

    Returns a new Array by removing duplicate values in self.

  • #uniq(& : T -> ) : Array(T)

    Returns a new Array by removing duplicate values in self, using the block's value for comparison.

  • #uniq! : self

    Removes duplicate elements from self.

  • #uniq!(& : T -> ) : self

    Removes duplicate elements from self, using the block's value for comparison.

  • #unsafe_fetch(index : Int) : T

    Returns the element at the given index, without doing any bounds check.

  • #unsafe_put(index : Int, value : T)

    Sets the element at the given index to value, without doing any bounds check.

  • #unshift(object : T) : self

    Prepend.

  • #unshift(*values : T) : self

    Prepend multiple values.

  • #unstable_sort : Array(T)

    Returns a new instance with all elements sorted based on the return value of their comparison method T#<=> (see Comparable#<=>), using an unstable sort algorithm.

  • #unstable_sort(&block : T, T -> U) : Array(T) forall U

    Returns a new instance with all elements sorted based on the comparator in the given block, using an unstable sort algorithm.

  • #unstable_sort! : self

    Sorts all elements in self based on the return value of the comparison method T#<=> (see Comparable#<=>), using an unstable sort algorithm.

  • #unstable_sort!(&block : T, T -> U) : self forall U

    Sorts all elements in self based on the comparator in the given block, using an unstable sort algorithm.

  • #unstable_sort_by(&block : T -> _) : Array(T)

    Returns a new instance with all elements sorted by the output value of the block.

  • #unstable_sort_by!(&block : T -> _) : Array(T)

    Sorts all elements in self by the output value of the block.

Constructor Detail

def self.additive_identity : self #

Returns the additive identity of this type.

This is an empty array.

If you are looking for more details, kindly visit Crystal Array.


Class Method Detail

def self.from_yaml(string_or_io : String | IO, &) #

Instance Method Detail

def each_repeated_permutation(size : Int = self.size, reuse = false, &) : Nil #
def repeated_permutations(size : Int = self.size) : Array(Array(T)) #

Comments

0

0/2000