class Array(T)

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)

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 that is reallocated when elements are pushed to it and 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} #=> [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

Superclass hierarchy

Object
Reference
Array(T)

Included Modules

Comparable(Array), Enumerable(T), Iterable

Defined in:

Class Method Summary

Instance Method Summary

Class Method Detail

def self.build(capacity : Int, &block)

Creates a new Array, allocating an internal buffer with the given capacity, and yielding that buffer. The block must return the desired length of the array.

This method is unsafe, but is usually used to initialize the buffer by passing it to a C function.

Array.build(3) do |buffer|
  LibSome.fill_buffer_and_return_number_of_elements_filled(buffer)
end

def self.from_json(string_or_io, &block)

def self.new(pull : JSON::PullParser)

def self.new(pull : JSON::PullParser, &block)

def self.new(size, &block : Int32 -> T)

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

Array.new(3) { |i| (i + 1) ** 2 } #=> [1, 4, 9]

ary = Array.new(3) { [1] }
puts ary #=> [[1], [1], [1]]
ary[0][0] = 2
puts ary #=> [[2], [1], [1]]

def self.new(size, value : T)

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

Array.new(3, 'a') #=> ['a', 'a', 'a']

ary = Array.new(3, [1])
puts ary #=> [[1], [1], [1]]
ary[0][0] = 2
puts ary #=> [[2], [2], [2]]

def self.new(initial_capacity = 3 : Int)

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

The initial_capacity is useful to avoid unnecesary reallocations of the internal buffer in case of growth. If you have an estimate of the maxinum number of elements an array will hold, you should initialize it with that capacity for improved execution performance.

ary = Array(Int32).new(5)
ary.length #=> 0

Instance Method Detail

def &(other : Array(U))

Set intersection: returns a new array containing elements common to the two arrays, excluding any duplicates. The order is preserved from the original array.

[ 1, 1, 3, 5 ] & [ 1, 2, 3 ]                 #=> [ 1, 3 ]
[ 'a', 'b', 'b', 'z' ] & [ 'a', 'b', 'c' ]   #=> [ 'a', 'b' ]

See also: #uniq.


def *(times : Int)

Repetition: Returns a new array built by concatenating times copies of ary.

[ "a", "b", "c" ] * 2   #=> [ "a", "b", "c", "a", "b", "c" ]

def +(other : Array(U))

Concatenation. Returns a new array built by concatenating two arrays together to create a third. The type of the new array is the union of the types of both the other arrays.

[1,2] + ["a"] # => [1,2,"a"] of (Int32 | String)
[1,2] + [2,3] # => [1,2,2,3]

def -(other : Array(U))

Difference. Returns a new array that is a copy of the original, removing any items that appear in other. The order of the original array is preserved.

[1,2,3] - [2,1] # => [3]

def <<(value : T)

Append. Alias for #push.

a = [1,2]
a << 3 # => [1,2,3]

def <=>(other : Array)

Combined comparison operator. Returns 0 if the first array equals the second, 1 if the first is greater than the second and -1 if the first is smaller than the second.

It compares the elements of both arrays in the same position using the #<=> operator, as soon as one of such comparisons returns a non zero value, that result is the return value of the whole comparison.

If all elements are equal, the comparison is based on the length of the arrays.

[8] <=> [1,2,3] # => 1
[2] <=> [4,2,3] # => -1
[1,2] <=> [1,2] # => 0

def ==(other : Array)

Equality. Returns true if it is passed an Array and #equals? returns true for both arrays, the caller and the argument.

ary = [1,2,3]
ary == [1,2,3] # => true
ary == [2,3]   # => false

def [](start : Int, count : Int)

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

Negative indices count backward from the end of the array (-1 is the last element). Aditionally, an empty array is returned when the starting index for an element range is at the end of the array.

Raises IndexError if the starting index is out of range.

a = [ "a", "b", "c", "d", "e" ]
a[-3, 3] # => ["c", "d", "e"]
a[6, 1] # => Index Error
a[1, 2] # => ["b", "c"]
a[5, 1] # => []

def [](index : Int)

Returns the element at the given index.

Negative indices can be used to start counting from the end of the array. Raises IndexError if trying to access an element outside the array's range.

ary = ['a', 'b', 'c']
ary[0]  #=> 'a'
ary[2]  #=> 'c'
ary[-1] #=> 'c'
ary[-2] #=> 'b'

ary[3]  # raises IndexError
ary[-4] # raises IndexError

def [](range : Range)

Returns all elements that are within the given range

Negative indices count backward from the end of the array (-1 is the last element). Aditionally, an empty array is returned when the starting index for an element range is at the end of the array.

Raises IndexError if the starting index is out of range.

a = [ "a", "b", "c", "d", "e" ]
a[1..3] # => ["b", "c", "d"]
a[4..7] # => ["e"]
a[6..10] # => Index Error
a[5..10] # => []
a[-2...-1] # => ["d"]

def []=(index : Int, value : T)

Sets the given value at the given index.

Raises IndexError if the array had no previous value at the given index.

ary = [1,2,3]
ary[0] = 5
p ary # => [5,2,3]

ary[3] = 5 # => IndexError

def []?(index : Int)

Returns the element at the given index.

Negative indices can be used to start counting from the end of the array. Returns nil if trying to access an element outside the array's range.

ary = ['a', 'b', 'c']
ary[0]?  #=> 'a'
ary[2]?  #=> 'c'
ary[-1]? #=> 'c'
ary[-2]? #=> 'b'

ary[3]?  # nil
ary[-4]? # nil

def at(index : Int)

Returns the element at the given index, if in bounds, otherwise raises IndexError.

a = [:foo, :bar]
a.at(0) #=> :foo
a.at(2) #=> IndexError

def at(index : Int, &block)

Returns the element at the given index, if in bounds, otherwise executes the given block and returns its value.

a = [:foo, :bar]
a.at(0) { :baz } #=> :foo
a.at(2) { :baz } #=> :baz

def clear

Removes all elements from self.

a = [ "a", "b", "c", "d", "e" ]
a.clear    #=> []

def clone

Returns a new Array that has this array's elements cloned. That is, it returns a deep copy of this array.

Use #dup if you want a shallow copy.

ary = [[1, 2], [3, 4]]
ary2 = ary.clone
ary[0][0] = 5
puts ary  #=> [[5, 2], [3, 4]]
puts ary2 #=> [[1, 2], [3, 4]]

ary2 << [7, 8]
puts ary  #=> [[5, 2], [3, 4]]
puts ary2 #=> [[1, 2], [3, 4], [7, 8]]

def compact

Returns a copy of self with all nil elements removed.

["a", nil, "b", nil, "c", nil].compact #=> ["a", "b", "c"]

def compact!

Removes nil elements from this array.

ary = ["a", nil, "b", nil, "c"]
ary.compact!
ary          #=> ["a", "b", "c"]

def concat(other : Array)

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

ary = ["a", "b"]
ary.concat(["c", "d"])
ary                    #=> ["a", "b", "c", "d"]

def concat(other : Enumerable)

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

ary = ["a", "b"]
ary.concat(["c", "d"])
ary                    #=> ["a", "b", "c", "d"]

def count

Same as #length.


def delete(obj)

Deletes all items from self that are equal to obj.

a = ["a", "b", "b", "b", "c"]
a.delete("b")
a #=> ["a", "c"]

def delete_at(index : Int)

def delete_if(&block)

def dup

Returns a new Array that has exactly this array's elements. That is, it returns a shallow copy of this array.

Use #clone if you want a deep copy.

ary = [[1, 2], [3, 4]]
ary2 = ary.dup
ary[0][0] = 5
puts ary  #=> [[5, 2], [3, 4]]
puts ary2 #=> [[5, 2], [3, 4]]

ary2 << [7, 8]
puts ary  #=> [[5, 2], [3, 4]]
puts ary2 #=> [[5, 2], [3, 4], [7, 8]]

def each(&block)

def each

def each_index

def each_index(&block)

def each_permutation(size = length : Int, &block)

Yields each possible permutation of size n of this array.

a = [1, 2, 3]
sums = [] of Int32
a.permutation(2) { |p| sums << p.sum } #=> [1, 2, 3]
sums #=> [3, 4, 3, 5, 4, 5]

def empty?

def equals?(other : Array, &block)

def fill(value : T, from : Int, size : Int)

def fill(&block)

def fill(value : T, from : Int)

def fill(value : T)

def fill(value : T, range : Range(Int, Int))

def fill(from : Int, size : Int, &block)

def fill(from : Int, &block)

def fill(range : Range(Int, Int), &block)

def first(&block)

def first

def first?

def hash

def insert(index : Int, obj : T)

def inspect(io : IO)

def last

def last(&block)

def last?

def length

Returns the number of elements in the array.

[:foo, :bar].length #=> 2

def map(&block : T -> U)

def map!(&block)

def map_with_index(&block : T, Int32 -> U)

def permutations(size = length : Int)

Returns an Array with all possible permutations of the given size.

a = [1, 2, 3]
a.permutation    #=> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
a.permutation(1) #=> [[1],[2],[3]]
a.permutation(2) #=> [[1,2],[1,3],[2,1],[2,3],[3,1],[3,2]]
a.permutation(3) #=> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
a.permutation(0) #=> [[]]
a.permutation(4) #=> []

def pop(n)

def pop(&block)

def pop

def pop?

def product(ary, &block)

def product(ary : Array(U))

def push(*values : T)

Append multiple values. The same as #push, but takes an arbitrary number of values to push into the array.


def push(value : T)

Append. Pushes one value to the end of the array, given that the type of the value is T (which might be a type or a union of types). This expression returns the array iself, so several of them can be chained. See #pop for the opposite effect.

a = ["a", "b"]
a.push("c") # => ["a", "b", "c"]
a.push(1) # => Errors, because the array only accepts String

a = ["a", "b"] of (Int32|String)
a.push("c") # => ["a", "b", "c"]
a.push(1) # => ["a", "b", "c", 1]

def reject!(&block)

def replace(other : Array)

def reverse

def reverse!

def reverse_each

def reverse_each(&block)

def rindex(value)

def rindex(&block)

def sample(n)

def sample

def select!(&block)

def shift(n)

def shift

def shift(&block)

def shift?

def shuffle

def shuffle!

def size

def sort

def sort(&block : T, T -> Int32)

def sort!(&block : T, T -> Int32)

def sort!

def sort_by(&block : T -> _)

def sort_by!(&block : T -> _)

def swap(index0, index1)

def to_a

def to_json(io)

def to_s(io : IO)

def to_set

def to_unsafe

def transpose

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

a = [[:a, :b], [:c, :d], [:e, :f]]
a.transpose   # => [[:a, :c, :e], [:b, :d, :f]]
a             # => [[:a, :b], [:c, :d], [:e, :f]]

def uniq(&block : T -> _)

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

a = [{"student","sam"}, {"student","george"}, {"teacher","matz"}]
a.uniq { |s| s[0] } # => [{"student", "sam"}, {"teacher", "matz"}]
a                   # => [{"student", "sam"}, {"student", "george"}, {"teacher", "matz"}]

def uniq

Returns a new array by removing duplicate values in self.

a = [ "a", "a", "b", "b", "c" ]
a.uniq   # => ["a", "b", "c"]
a        # => [ "a", "a", "b", "b", "c" ]

def uniq!(&block)

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

a = [{"student","sam"}, {"student","george"}, {"teacher","matz"}]
a.uniq! { |s| s[0] } # => [{"student", "sam"}, {"teacher", "matz"}]
a                    # => [{"student", "sam"}, {"teacher", "matz"}]

def uniq!

Removes duplicate elements from self. Returns self.

a = [ "a", "a", "b", "b", "c" ]
a.uniq!   # => ["a", "b", "c"]
a         # => ["a", "b", "c"]

def unshift(obj : T)

def update(index : Int, &block)

def values_at(*indexes : Int)

Returns a tuple populated with the elements at the given indexes. Raises if any index is invalid.

["a", "b", "c", "d"].values_at(0, 2) #=> {"a", "c"}

def zip(other : Array(U))

def zip(other : Array, &block)

def zip?(other : Array(U))

def zip?(other : Array, &block)

def |(other_ary : Array(U))

Set union: returns a new array by joining ary with other_ary, excluding any duplicates and preserving the order from the original array.

[ "a", "b", "c" ] | [ "c", "d", "a" ]    #=> [ "a", "b", "c", "d" ]

See also: #uniq.