class

Array(T)

Inherits Comparable / Indexable::Mutable / Indexable / Enumerable / Iterable / Reference / Object

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

Constructors

additive_identity

Returns the additive identity of this type.

This is an empty array.

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

Creates a new Array, allocating an internal buffer with the given capacity, and yielding that buffer. The given block must return the desired size 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
Source
new(size : Int, 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']

WARNING: The initial value is filled into the array as-is. It gets neither duplicated nor cloned. For types with reference semantics this means every item will point to the same object.

ary = Array.new(3, [1])
ary # => [[1], [1], [1]]
ary[0][0] = 2
ary # => [[2], [2], [2]]
  • .new(Int, & : Int32 -> T) is an alternative that allows using a different initial value for each position.
Source
new(initial_capacity : Int)

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

The initial_capacity is useful to avoid unnecessary reallocations of the internal buffer in case of growth. If you have an estimate of the maximum number of elements an array will hold, the array should be initialized with that capacity for improved performance.

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

Creates a new empty Array.

Source
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.

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

ary = Array.new(3) { [1] }
ary # => [[1], [1], [1]]
ary[0][0] = 2
ary # => [[2], [1], [1]]
Source
new(pull : JSON::PullParser, &)
Source

Class methods

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

Yields each ordered combination of the elements taken from each of the arrays as Arrays. Traversal of elements starts from the last given array.

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

Yields each ordered combination of the elements taken from each of the arrays as Arrays. Traversal of elements starts from the last given array.

Source
from_json(string_or_io, &) : Nil

Parses a String or IO denoting a JSON array, yielding each of its elements to the given block. This is useful for decoding an array and processing its elements without creating an Array in memory, which might be expensive.

require "json"

Array(Int32).from_json("[1, 2, 3]") do |element|
  puts element
end

Output:

1
2
3

To parse and get an Array, use the block-less overload.

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

Returns an Array of all ordered combinations of elements taken from each of the arrays as Arrays. Traversal of elements starts from the last given array.

Source
product(*arrays : Array)

Returns an Array of all ordered combinations of elements taken from each of the arrays as Arrays. Traversal of elements starts from the last given array.

Source

Instance methods

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

Set intersection: returns a new Array containing elements common to self and other, excluding any duplicates. The order is preserved from self.

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

See also: #uniq.

Source
*(times : Int) : Array(T)

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

["a", "b", "c"] * 2 # => [ "a", "b", "c", "a", "b", "c" ]
Source
+(other : Array(U)) : Array(T | U) forall U

Concatenation. Returns a new Array built by concatenating self and other. The type of the new array is the union of the types of both the original arrays.

[1, 2] + ["a"]  # => [1,2,"a"] of (Int32 | String)
[1, 2] + [2, 3] # => [1,2,2,3]
Source
-(other : Array(U)) : Array(T) forall U

Difference. Returns a new Array that is a copy of self, removing any items that appear in other. The order of self is preserved.

[1, 2, 3] - [2, 1] # => [3]
Source
<<(value : T) : self

Append. Alias for push.

a = [1, 2]
a << 3 # => [1,2,3]
Source
<=>(other : Array)

Combined comparison operator.

Returns -1, 0 or 1 depending on whether self is less than other, equals other or is greater than other.

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 comparison.

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

[8] <=> [1, 2, 3] # => 1
[2] <=> [4, 2, 3] # => -1
[1, 2] <=> [1, 2] # => 0
Source
==(other : Array) : Bool

Equality. Returns true if each element in self is equal to each corresponding element in other.

ary = [1, 2, 3]
ary == [1, 2, 3] # => true
ary == [2, 3]    # => false
Source
==(other : JSON::Any)
Source
==(other : YAML::Any)
Source
==(other) : Bool

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

Source
[](start : Int, count : Int) : Array(T)

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

Negative start is added to self.size, thus it's treated as index counting from the end of the array, -1 designating the last element.

Raises IndexError if start index is out of bounds. Raises ArgumentError if count is negative.

a = ["a", "b", "c", "d", "e"]
a[-3, 3] # => ["c", "d", "e"]
a[1, 2]  # => ["b", "c"]
a[5, 1]  # => []
a[6, 1]  # raises IndexError
Source
[](range : Range) : Array(T)

Returns all elements that are within the given range.

The first element in the returned array is self[range.begin] followed by the next elements up to index range.end (or self[range.end - 1] if the range is exclusive). If there are fewer elements in self, the returned array is shorter than range.size.

a = ["a", "b", "c", "d", "e"]
a[1..3] # => ["b", "c", "d"]
# range.end > array.size
a[3..7] # => ["d", "e"]

Open ended ranges are clamped at the start and end of the array, respectively.

# open ended ranges
a[2..] # => ["c", "d", "e"]
a[..2] # => ["a", "b", "c"]

Negative range values are added to self.size, thus they are treated as indices counting from the end of the array, -1 designating the last element.

# negative indices, both ranges are equivalent for `a`
a[1..3]   # => ["b", "c", "d"]
a[-4..-2] # => ["b", "c", "d"]
# Mixing negative and positive indices, both ranges are equivalent for `a`
a[1..-2] # => ["b", "c", "d"]
a[-4..3] # => ["b", "c", "d"]

Raises IndexError if the start index is out of range (range.begin > self.size || range.begin < -self.size). If range.begin == self.size an empty array is returned. If range.begin > range.end, an empty array is returned.

# range.begin > array.size
a[6..10] # raise IndexError
# range.begin == array.size
a[5..10] # => []
# range.begin > range.end
a[3..1]   # => []
a[-2..-4] # => []
a[-2..1]  # => []
a[3..-4]  # => []
Source
[]=(start : Int, count : Int, values : Array(T))

Replaces a subrange with the elements of the given array.

a = [1, 2, 3, 4, 5]
a[1, 3] = [6, 7, 8]
a # => [1, 6, 7, 8, 5]

a = [1, 2, 3, 4, 5]
a[1, 3] = [6, 7]
a # => [1, 6, 7, 5]

a = [1, 2, 3, 4, 5]
a[1, 3] = [6, 7, 8, 9, 10]
a # => [1, 6, 7, 8, 9, 10, 5]
Source
[]=(start : Int, count : Int, value : T) : T

Replaces a subrange with a single value. All elements in the range start...start+count are removed and replaced by a single element value.

If count is zero, value is inserted at start.

Negative values of start count from the end of the array.

a = [1, 2, 3, 4, 5]
a[1, 3] = 6
a # => [1, 6, 5]

a = [1, 2, 3, 4, 5]
a[1, 0] = 6
a # => [1, 6, 2, 3, 4, 5]
Source
[]=(range : Range, values : Array(T))

Replaces a subrange with the elements of the given array.

a = [1, 2, 3, 4, 5]
a[1..3] = [6, 7, 8]
a # => [1, 6, 7, 8, 5]

a = [1, 2, 3, 4, 5]
a[1..3] = [6, 7]
a # => [1, 6, 7, 5]

a = [1, 2, 3, 4, 5]
a[1..3] = [6, 7, 8, 9, 10]
a # => [1, 6, 7, 8, 9, 10, 5]

a = [1, 2, 3, 4, 5]
a[2..] = [6, 7, 8, 9, 10]
a # => [1, 2, 6, 7, 8, 9, 10]
Source
[]=(range : Range, value : T)

Replaces a subrange with a single value.

a = [1, 2, 3, 4, 5]
a[1..3] = 6
a # => [1, 6, 5]

a = [1, 2, 3, 4, 5]
a[1...1] = 6
a # => [1, 6, 2, 3, 4, 5]

a = [1, 2, 3, 4, 5]
a[2...] = 6
a # => [1, 2, 6]
Source
[]=(values : Array(T), *, index start : Int, count : Int)

Replaces a subrange with the elements of the given array.

a = [1, 2, 3, 4, 5]
a[1, 3] = [6, 7, 8]
a # => [1, 6, 7, 8, 5]

a = [1, 2, 3, 4, 5]
a[1, 3] = [6, 7]
a # => [1, 6, 7, 5]

a = [1, 2, 3, 4, 5]
a[1, 3] = [6, 7, 8, 9, 10]
a # => [1, 6, 7, 8, 9, 10, 5]
Source
[]=(value : T, *, index start : Int, count : Int)

Replaces a subrange with a single value. All elements in the range start...start+count are removed and replaced by a single element value.

If count is zero, value is inserted at start.

Negative values of start count from the end of the array.

a = [1, 2, 3, 4, 5]
a[1, 3] = 6
a # => [1, 6, 5]

a = [1, 2, 3, 4, 5]
a[1, 0] = 6
a # => [1, 6, 2, 3, 4, 5]
Source
[]?(start : Int, count : Int) : Array(T) | Nil

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

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

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

a = ["a", "b", "c", "d", "e"]
a[6..10]? # => nil
a[6..]?   # => nil
Source
|(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.

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

See also: #uniq.

Source
clear

Removes all elements from self.

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

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

Use #dup if you want a shallow copy.

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

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

Returns a copy of self with all nil elements removed.

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

Removes all nil elements from self and returns self.

ary = ["a", nil, "b", nil, "c"]
ary.compact!
ary # => ["a", "b", "c"]
Source
concat(other : Indexable) : self

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

ary = ["a", "b"]
ary.concat(["c", "d"])
ary # => ["a", "b", "c", "d"]
Source
concat(other : Enumerable) : self

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

ary = ["a", "b"]
ary.concat(["c", "d"])
ary # => ["a", "b", "c", "d"]
Source
delete(obj) : T | Nil

Removes all items from self that are equal to obj.

Returns the last found element that was equal to obj, if any, or nil if not found.

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

a.delete("x") # => nil
a             # => ["a", "c"]
Source
delete_at(start : Int, count : Int) : self

Removes count elements from self starting at start. If the size of self is less than count, removes values to the end of the array without error. Returns an array of the removed elements with the original order of self preserved. Raises IndexError if start is out of range.

a = ["ant", "bat", "cat", "dog"]
a.delete_at(1, 2)  # => ["bat", "cat"]
a                  # => ["ant", "dog"]
a.delete_at(99, 1) # raises IndexError
Source
delete_at(index : Int) : T

Removes the element at index, returning that element. Raises IndexError if index is out of range.

a = ["ant", "bat", "cat", "dog"]
a.delete_at(2)  # => "cat"
a               # => ["ant", "bat", "dog"]
a.delete_at(99) # raises IndexError
Source
delete_at(range : Range) : self

Removes all elements within the given range. Returns an array of the removed elements with the original order of self preserved. Raises IndexError if the index is out of range.

a = ["ant", "bat", "cat", "dog"]
a.delete_at(1..2)    # => ["bat", "cat"]
a                    # => ["ant", "dog"]
a.delete_at(99..100) # raises IndexError
Source
delete_at(*, index start : Int, count : Int) : self

Removes count elements from self starting at start. If the size of self is less than count, removes values to the end of the array without error. Returns an array of the removed elements with the original order of self preserved. Raises IndexError if start is out of range.

a = ["ant", "bat", "cat", "dog"]
a.delete_at(1, 2)  # => ["bat", "cat"]
a                  # => ["ant", "dog"]
a.delete_at(99, 1) # raises IndexError
Source
dup

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

Use #clone if you want a deep copy.

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

ary2 << [7, 8]
ary  # => [[5, 2], [3, 4]]
ary2 # => [[5, 2], [3, 4], [7, 8]]
Source
each_repeated_permutation(size : Int = self.size, reuse = false, &) : Nil
Source
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. Returns self.

Negative values of start count from the end of the array.

Raises IndexError if start is outside the array range.

a = [1, 2, 3, 4]
a.fill(2) { |i| i * i } # => [1, 2, 4, 9]
Source
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. Returns self.

Negative values of start count from the end of the array.

Raises IndexError if start is outside the array range.

a = [1, 2, 3, 4]
a.fill(2) { |i| i * i } # => [1, 2, 4, 9]
Source
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. Returns self.

Negative values of start count from the end of the array.

Raises IndexError if start is outside the array range.

Has no effect if count is zero or negative.

a = [1, 2, 3, 4, 5, 6]
a.fill(2, 2) { |i| i * i } # => [1, 2, 4, 9, 5, 6]
Source
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. Returns self.

Negative values of start count from the end of the container.

Raises IndexError if the start index is out of range.

Raises ArgumentError if count is negative.

array = [1, 2, 3, 4, 5]
array.fill(9, 2, 2) # => [1, 2, 9, 9, 5]
array               # => [1, 2, 9, 9, 5]
Source
fill(value : T, start : Int) : self

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

Negative values of start count from the end of the array.

a = [1, 2, 3, 4, 5]
a.fill(9, 2) # => [1, 2, 9, 9, 9]
Source
fill(value : T, range : Range) : self

Replaces every element in range with value. Returns self.

Negative values of from count from the end of the array.

a = [1, 2, 3, 4, 5]
a.fill(9, 2..3) # => [1, 2, 9, 9, 5]
Source
fill(value : T) : self

Replaces every element in self with the given value. Returns self.

array = [1, 2, 3, 4]
array.fill(2) # => [2, 2, 2, 2]
array         # => [2, 2, 2, 2]
Source
fill(value : T, *, from start : Int) : self

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

Negative values of start count from the end of the array.

a = [1, 2, 3, 4, 5]
a.fill(9, 2) # => [1, 2, 9, 9, 9]
Source
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. Returns self.

Negative values of start count from the end of the container.

Raises IndexError if the start index is out of range.

Raises ArgumentError if count is negative.

array = [1, 2, 3, 4, 5]
array.fill(9, 2, 2) # => [1, 2, 9, 9, 5]
array               # => [1, 2, 9, 9, 5]
Source
first(n : Int) : Array(T)

Returns the first n elements of the array.

[1, 2, 3].first(2) # => [1, 2]
[1, 2, 3].first(4) # => [1, 2, 3]
Source
flatten

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

That is, for every element that is an array or an iterator, extract its elements into the new array.

s = [1, 2, 3]          # => [1, 2, 3]
t = [4, 5, 6, [7, 8]]  # => [4, 5, 6, [7, 8]]
u = [9, [10, 11].each] # => [9, #<Indexable::ItemIterator>]
a = [s, t, u, 12, 13]  # => [[1, 2, 3], [4, 5, 6, [7, 8]], 9, #<Indexable::ItemIterator>, 12, 13]
a.flatten              # => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
Source
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.

[1, 2, 3, 1, 2, 3].index(2, offset: 2) # => 4
Source
insert(index : Int, object : T) : self

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

Negative values of index count from the end of the array.

a = ["a", "b", "c"]
a.insert(0, "x")  # => ["x", "a", "b", "c"]
a.insert(2, "y")  # => ["x", "a", "y", "b", "c"]
a.insert(-1, "z") # => ["x", "a", "y", "b", "c", "z"]
Source
insert_all(index : Int, other : Indexable) : self

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

This method shifts the element currently at index (if any) and any subsequent elements to the right, increasing their indices. If the value of index is negative, counting starts from the end of the array. For example, -1 indicates insertion after the last element, -2 before the last element.

Raises IndexError if the index is out of bounds.

fruits = ["Apple"]
newFruits = ["Dragonfruit", "Elderberry"]

fruits.insert_all(1, newFruits)             # => ["Apple", "Dragonfruit", "Elderberry"]
fruits.insert_all(-3, ["Banana", "Cherry"]) # => ["Apple", "Banana", "Cherry", "Dragonfruit", "Elderberry"]

fruits.insert_all(6, ["invalid"])  # raises IndexError
fruits.insert_all(-7, ["indices"]) # raises IndexError
Source
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.

class Person
  def initialize(@name : String, @age : Int32)
  end
end

Person.new("John", 32).inspect # => #<Person:0x10fd31f20 @name="John", @age=32>
Source
last(n : Int) : Array(T)

Returns the last n elements of the array.

[1, 2, 3].last(2) # => [2, 3]
[1, 2, 3].last(4) # => [1, 2, 3]
Source
map

Optimized version of Enumerable#map.

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

Optimized version of Enumerable#map_with_index.

Accepts an optional offset parameter, which tells it to start counting from there.

gems = ["crystal", "pearl", "diamond"]
results = gems.map_with_index { |gem, i| "#{i}: #{gem}" }
results # => ["0: crystal", "1: pearl", "2: diamond"]
Source
pop(n : Int) : Array(T)

Removes the last n values from self, at index size - 1. This method returns an array of the removed values, with the original order preserved.

If n is greater than the size of self, all values will be removed from self without raising an error.

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

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

See also: #truncate.

Source
pop

Removes the last value from self, at index size - 1. This method returns the removed value. Raises IndexError if array is of 0 size.

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

See also: #truncate.

Source
pop

Removes the last value from self. If the array is empty, the given block is called.

a = [1]
a.pop { "Testing" } # => 1
a.pop { "Testing" } # => "Testing"

See also: #truncate.

Source
pop?

Like pop, but returns nil if self is empty.

See also: #truncate.

Source
pretty_print(pp) : Nil
Source
product(ary : Array(U)) forall U

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

Source
product(enumerable : Enumerable, &)

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

Source
push(value : T) : self

Append. Pushes one value to the end of self, given that the type of the value is T (which might be a single type or a union of types). This method returns self, so several calls 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]
Source
push(*values : T) : self

Append multiple values. The same as push, but takes an arbitrary number of values to push into self. Returns self.

a = ["a"]
a.push("b", "c") # => ["a", "b", "c"]
Source
reject!

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

ary = [1, 6, 2, 4, 8]
ary.reject! { |x| x > 3 }
ary # => [1, 2]

See also: Array#reject.

Source
reject!(pattern) : self

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

ary = [1, 6, 2, 4, 8]
ary.reject!(3..7)
ary # => [1, 2, 8]

See also: Array#select!.

Source
remaining_capacity
Source
repeated_permutations(size : Int = self.size) : Array(Array(T))
Source
replace(other : Array) : self

Replaces the contents of self with the contents of other. This resizes the Array to a greater capacity but does not free memory if the given array is smaller.

a1 = [1, 2, 3]
a1.replace([1])
a1                    # => [1]
a1.remaining_capacity # => 3
a2 = [1]
a2.replace([1, 2, 3])
a2 # => [1, 2, 3]
Source
reverse

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

a = [1, 2, 3]
a.reverse # => [3, 2, 1]
Source
rotate(n = 1) : Array(T)

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

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
a.rotate    # => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
a.rotate(1) # => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
a.rotate(3) # => [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]
a           # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Source
rotate!(n : Int = 1) : self

Shifts all elements of self to the left n times. Returns self.

a1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
a2 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
a3 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

a1.rotate!
a2.rotate!(1)
a3.rotate!(3)

a1 # => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
a2 # => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
a3 # => [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]
Source
select!

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

ary = [1, 6, 2, 4, 8]
ary.select! { |x| x > 3 }
ary # => [6, 4, 8]

See also: Array#select.

Source
select!(pattern) : self

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

ary = [1, 6, 2, 4, 8]
ary.select!(3..7)
ary # => [6, 4]

See also: Array#reject!.

Source
shift(n : Int) : Array(T)

Removes the first n values of self, starting at index 0. This method returns an array of the removed values.

If n is greater than the size of self, all values will be removed from self without raising an error.

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

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

See also: #truncate.

Source
shift

Removes the first value of self, at index 0. This method returns the removed value. If the array is empty, it raises IndexError.

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

See also: #truncate.

Source
shift

Removes the first value of self, at index 0, or otherwise invokes the given block. This method returns the removed value. If the array is empty, it invokes the given block and returns its value.

a = ["a"]
a.shift { "empty!" } # => "a"
a                    # => []
a.shift { "empty!" } # => "empty!"
a                    # => []

See also: #truncate.

Source
shift?

Removes the first value of self, at index 0. This method returns the removed value. If the array is empty, it returns nil without raising any error.

a = ["a", "b"]
a.shift? # => "a"
a        # => ["b"]
a.shift? # => "b"
a        # => []
a.shift? # => nil
a        # => []

See also: #truncate.

Source
shuffle(random : Random | Nil = nil) : Array(T)

Returns a new instance with all elements in the collection randomized.

See Indexable::Mutable#shuffle! for details.

Source
size

Returns the number of elements in the array.

[:foo, :bar].size # => 2
Source
skip(count : Int) : Array(T)

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

If count is bigger than the number of elements in the array, returns an empty array.

[1, 2, 3, 4, 5, 6].skip(3) # => [4, 5, 6]
Source
sort

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.

a = [3, 1, 2]
a.sort # => [1, 2, 3]
a      # => [3, 1, 2]

See Indexable::Mutable#sort! for details on the sorting mechanism.

Raises ArgumentError if the comparison between any two elements returns nil.

Source
sort

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

a = [3, 1, 2]
b = a.sort { |a, b| b <=> a }

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

See Indexable::Mutable#sort!(&block : T, T -> U) for details on the sorting mechanism.

Raises ArgumentError if for any two elements the block returns nil.

Source
sort!

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

a = [3, 1, 2]
a.sort!
a # => [1, 2, 3]

This sort operation modifies self. See #sort for a non-modifying option that allocates a new instance.

See Slice#sort! for details on the implementation.

Raises ArgumentError if the comparison between any two elements returns nil.

Source
sort!

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

The block must implement a comparison between two elements a and b, where a < b returns -1, a == b returns 0, and a > b returns 1. The comparison operator <=> can be used for this.

a = [3, 1, 2]
# This is a reverse sort (forward sort would be `a <=> b`)
a.sort! { |a, b| b <=> a }
a # => [3, 2, 1]

This sort operation modifies self. See #sort(&block : T, T -> U) for a non-modifying option that allocates a new instance.

See Slice#sort!(&block : T, T -> U) for details on the implementation.

Raises ArgumentError if for any two elements the block returns nil.

Source
sort_by

Returns a new instance with all elements sorted by the output value of the block. The output values are compared via the comparison method T#<=> (see Comparable#<=>), using a stable sort algorithm.

a = %w(apple pear fig)
b = a.sort_by { |word| word.size }
b # => ["fig", "pear", "apple"]
a # => ["apple", "pear", "fig"]

If stability is expendable, #unstable_sort_by(&block : T -> _) provides a performance advantage over stable sort.

See Indexable::Mutable#sort_by!(&block : T -> _) for details on the sorting mechanism.

Raises ArgumentError if the comparison between any two comparison values returns nil.

Source
sort_by!

Sorts all elements in self by the output value of the block. The output values are compared via the comparison method #<=> (see Comparable#<=>), using a stable sort algorithm.

a = %w(apple pear fig)
a.sort_by! { |word| word.size }
a # => ["fig", "pear", "apple"]

This sort operation modifies self. See #sort_by(&block : T -> _) for a non-modifying option that allocates a new instance.

If stability is expendable, #unstable_sort_by!(&block : T -> _) provides a performance advantage over stable sort.

See #sort!(&block : T -> _) for details on the sorting mechanism.

Raises ArgumentError if the comparison between any two comparison values returns nil.

Source
to_a

Returns an Array with all the elements in the collection.

(1..5).to_a # => [1, 2, 3, 4, 5]
Source
to_json(json : JSON::Builder) : Nil
Source
to_s(io : IO) : Nil

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

The result resembles an array literal but it does not necessarily compile.

Each element is presented using its #inspect(io) result to avoid ambiguity.

Source
to_unsafe

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

This method is unsafe because it returns a pointer, and the pointed might eventually not be that of self if the array grows and its internal buffer is reallocated.

ary = [1, 2, 3]
ary.to_unsafe[0] # => 1
Source
to_yaml(yaml : YAML::Nodes::Builder) : Nil
Source
transpose

Assumes that self is an array of arrays 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]]
Source
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. Returns self.

Negative values of start count from the end of the array.

Raises IndexError if the start index is out of range.

Raises ArgumentError if count is negative.

a = [0, 1, 4, 9, 16, 25]
a.truncate(2, 3) # => [4, 9, 16]
a                # => [4, 9, 16]

See also: #pop, #shift.

Source
truncate(range : Range) : self

Removes all elements except those within the given range. Returns self.

a = [0, 1, 4, 9, 16, 25]
a.truncate(1..-3) # => [1, 4, 9]
a                 # => [1, 4, 9]
Source
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" ]
Source
uniq

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"}]
Source
uniq!

Removes duplicate elements from self. Returns self.

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

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"}]
Source
unsafe_fetch(index : Int) : T

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

Indexable makes sure to invoke this method with index in 0...size, so converting negative indices to positive ones is not needed here.

Clients never invoke this method directly. Instead, they access elements with #[](index) and #[]?(index).

This method should only be directly invoked if you are absolutely sure the index is in bounds, to avoid a bounds check for a small boost of performance.

Source
unsafe_put(index : Int, value : T)

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

Indexable::Mutable makes sure to invoke this method with index in 0...size, so converting negative indices to positive ones is not needed here.

Clients never invoke this method directly. Instead, they modify elements with #[]=(index, value).

This method should only be directly invoked if you are absolutely sure the index is in bounds, to avoid a bounds check for a small boost of performance.

Source
unshift(object : T) : self

Prepend. Adds object to the beginning of self, given that the type of the value is T (which might be a single type or a union of types). This method returns self, so several calls can be chained. See shift for the opposite effect.

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

a = ["a", "b"] of (Int32 | String)
a.unshift("c") # => ["c", "a", "b"]
a.unshift(1)   # => [1, "c", "a", "b"]
Source
unshift(*values : T) : self

Prepend multiple values. The same as unshift, but takes an arbitrary number of values to add to the array. Returns self.

Source
unstable_sort

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.

a = [3, 1, 2]
a.unstable_sort # => [1, 2, 3]
a               # => [3, 1, 2]

See Indexable::Mutable#unstable_sort! for details on the sorting mechanism.

Raises ArgumentError if the comparison between any two elements returns nil.

Source
unstable_sort

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

a = [3, 1, 2]
b = a.unstable_sort { |a, b| b <=> a }

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

See Indexable::Mutable#unstable_sort!(&block : T, T -> U) for details on the sorting mechanism.

Raises ArgumentError if for any two elements the block returns nil.

Source
unstable_sort!

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

a = [3, 1, 2]
a.unstable_sort!
a # => [1, 2, 3]

This sort operation modifies self. See #unstable_sort for a non-modifying option that allocates a new instance.

See Slice#unstable_sort! for details on the implementation.

Raises ArgumentError if the comparison between any two elements returns nil.

Source
unstable_sort!

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

The block must implement a comparison between two elements a and b, where a < b returns -1, a == b returns 0, and a > b returns 1. The comparison operator <=> can be used for this.

a = [3, 1, 2]
# This is a reverse sort (forward sort would be `a <=> b`)
a.unstable_sort! { |a, b| b <=> a }
a # => [3, 2, 1]

This sort operation modifies self. See #unstable_sort(&block : T, T -> U) for a non-modifying option that allocates a new instance.

See Slice#unstable_sort!(&block : T, T -> U) for details on the implementation.

Raises ArgumentError if for any two elements the block returns nil.

Source
unstable_sort_by

Returns a new instance with all elements sorted by the output value of the block. The output values are compared via the comparison method #<=> (see Comparable#<=>), using an unstable sort algorithm.

a = %w(apple pear fig)
b = a.unstable_sort_by { |word| word.size }
b # => ["fig", "pear", "apple"]
a # => ["apple", "pear", "fig"]

If stability is necessary, use #sort_by(&block : T -> _) instead.

See Indexable::Mutable#unstable_sort!(&block : T -> _) for details on the sorting mechanism.

Raises ArgumentError if the comparison between any two comparison values returns nil.

Source
unstable_sort_by!

Sorts all elements in self by the output value of the block. The output values are compared via the comparison method #<=> (see Comparable#<=>), using an unstable sort algorithm.

a = %w(apple pear fig)
a.unstable_sort_by! { |word| word.size }
a # => ["fig", "pear", "apple"]

This sort operation modifies self. See #unstable_sort_by(&block : T -> _) for a non-modifying option that allocates a new instance.

If stability is necessary, use #sort_by!(&block : T -> _) instead.

See #unstable_sort!(&block : T -> _) for details on the sorting mechanism.

Raises ArgumentError if the comparison between any two comparison values returns nil.

Source