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
Creates a new Array, allocating an internal buffer with the given capacity, and yielding that buffer.
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.
Creates a new Array of the given size filled with the same value in each position.
Creates a new empty Array backed by a buffer that is initially initial_capacity big.
Set intersection: returns a new array containing elements common to the two arrays, excluding any duplicates.
Repetition: Returns a new array built by concatenating times copies of ary.
Concatenation.
Difference.
Append.
Combined comparison operator.
Equality.
Returns count or less (if there aren't enough) elements starting at the given start index.
Returns the element at the given index.
Returns all elements that are within the given range
Sets the given value at the given index.
Returns the element at the given index.
Returns the element at the given index, if in bounds, otherwise raises IndexError.
Returns the element at the given index, if in bounds, otherwise executes the given block and returns its value.
Removes all elements from self.
Returns a new Array that has this array's elements cloned.
Returns a copy of self with all nil elements removed.
Removes nil elements from this array.
Appends the elements of other to self, and returns self.
Appends the elements of other to self, and returns self.
Same as #length.
Deletes all items from self that are equal to obj.
Returns a new Array that has exactly this array's elements.
Yields each possible permutation of size n of this array.
Returns the number of elements in the array.
Returns an Array with all possible permutations of the given size.
Append multiple values.
Append.
Assumes that self is an array of array and transposes the rows and columns.
Returns a new array by removing duplicate values in self, using the block's value for comparison.
Returns a new array by removing duplicate values in self.
Removes duplicate elements from self, using the block's value for comparison.
Removes duplicate elements from self.
Returns a tuple populated with the elements at the given indexes.
Set union: returns a new array by joining ary with other_ary, excluding any duplicates and preserving the order from the original array.
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)
endCreates 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]]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]]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 #=> 0Set 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.
Repetition: Returns a new array built by concatenating times copies of ary.
[ "a", "b", "c" ] * 2 #=> [ "a", "b", "c", "a", "b", "c" ]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]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]Append. Alias for #push.
a = [1,2]
a << 3 # => [1,2,3]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] # => 0Equality. 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] # => falseReturns 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] # => []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 IndexErrorReturns 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"]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 # => IndexErrorReturns 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]? # nilReturns the element at the given index, if in bounds,
otherwise raises IndexError.
a = [:foo, :bar]
a.at(0) #=> :foo
a.at(2) #=> IndexErrorReturns 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 } #=> :bazRemoves all elements from self.
a = [ "a", "b", "c", "d", "e" ]
a.clear #=> []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]]Returns a copy of self with all nil elements removed.
["a", nil, "b", nil, "c", nil].compact #=> ["a", "b", "c"]Removes nil elements from this array.
ary = ["a", nil, "b", nil, "c"]
ary.compact!
ary #=> ["a", "b", "c"]Appends the elements of other to self, and returns self.
ary = ["a", "b"]
ary.concat(["c", "d"])
ary #=> ["a", "b", "c", "d"]Appends the elements of other to self, and returns self.
ary = ["a", "b"]
ary.concat(["c", "d"])
ary #=> ["a", "b", "c", "d"]Same as #length.
Deletes all items from self that are equal to obj.
a = ["a", "b", "b", "b", "c"]
a.delete("b")
a #=> ["a", "c"]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]]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]Returns the number of elements in the array.
[:foo, :bar].length #=> 2Returns 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) #=> []Append multiple values. The same as #push, but takes an arbitrary number
of values to push into the array.
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]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]]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"}]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" ]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"}]Removes duplicate elements from self. Returns self.
a = [ "a", "a", "b", "b", "c" ]
a.uniq! # => ["a", "b", "c"]
a # => ["a", "b", "c"]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"}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.