class Array(T)
Overview
AnArray 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.
AnArray 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)
SeeArray literals in the language reference.
AnArray 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
AnArray 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 adynamic 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
Defined in:
array.crjson/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 givencapacity, and yielding that buffer. -
.new(size : Int, value : T)
Creates a new
Arrayof the givensize filled with the samevalue in each position. - .new(ctx : YAML::ParseContext, node : YAML::Nodes::Node)
-
.new(initial_capacity : Int)
Creates a new empty
Arraybacked by a buffer that is initiallyinitial_capacitybig. - .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
Arrayof the givensize and invokes the given block once for each index ofself, 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 thearrays 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 thearrays as
Arrays.DEPRECATED Use
Indexable.each_cartesian(indexables : Indexable(Indexable), reuse = false, &block)instead - .from_json(string_or_io, &) : Nil
- .from_yaml(string_or_io : String | IO, &)
-
.product(arrays : Array(Array))
Returns an
Arrayof all ordered combinations of elements taken from each of thearrays asArrays.DEPRECATED Use
Indexable.cartesian_product(indexables : Indexable(Indexable))instead -
.product(*arrays : Array)
Returns an
Arrayof all ordered combinations of elements taken from each of thearrays asArrays.DEPRECATED Use
Indexable.cartesian_product(indexables : Indexable(Indexable))instead
Instance Method Summary
-
#&(other : Array(U)) : Array(T) forall U
Set intersection: returns a new
Arraycontaining elements common toselfandother, excluding any duplicates. -
#*(times : Int) : Array(T)
Repetition: Returns a new
Arraybuilt by concatenatingtimes copies ofself. -
#+(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 aValuehere). -
#[](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 returnsnilif thestart index is out of range. -
#[]?(range : Range) : Array(T) | Nil
Like
#[](Range), but returnsnilifrange.beginis out of range. -
#|(other : Array(U)) : Array(T | U) forall U
Set union: returns a new
Arrayby joiningselfwithother, excluding any duplicates, and preserving the order fromself. -
#clear : self
Removes all elements from
self. -
#clone : Array(T)
Returns a new
Arraythat hasself's elements cloned. -
#compact
Returns a copy of
selfwith allnilelements removed. -
#compact! : self
Removes all
nilelements fromselfand returnsself. -
#concat(other : Indexable) : self
Appends the elements ofother to
self, and returnsself. -
#concat(other : Enumerable) : self
Appends the elements ofother to
self, and returnsself. -
#delete(obj) : T | Nil
Removes all items from
selfthat are equal toobj. -
#delete_at(start : Int, count : Int) : self
Removescount elements from
selfstarting atstart. -
#delete_at(index : Int) : T
Removes the element atindex, returning that element.
-
#delete_at(range : Range) : self
Removes all elements within the givenrange.
-
#delete_at(*, index start : Int, count : Int) : self
Removescount elements from
selfstarting atstart.DEPRECATED Use
#delete_at(start, count)instead -
#dup : Array(T)
Returns a new
Arraythat has exactlyself's elements. - #each_repeated_permutation(size : Int = self.size, reuse = false, &) : Nil
-
#fill(start : Int, & : Int32 -> T) : self
Yields each index of
self, starting atstart, 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 atstart, to the given block and then assigns the block's value in that position.DEPRECATED Use
#fill(start.., &)instead -
#fill(*, from start : Int, count : Int, & : Int32 -> T) : self
Yields each index of
self, starting atstart and justcount 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
Replacescount or less (if there aren't enough) elements starting at the givenstart index withvalue.
-
#fill(value : T, start : Int) : self
Replaces every element in
self, starting atstart, with the givenvalue.DEPRECATED Use
#fill(value, start..)instead -
#fill(value : T, range : Range) : self
Replaces every element inrange withvalue.
-
#fill(value : T) : self
Replaces every element in
selfwith the givenvalue. -
#fill(value : T, *, from start : Int) : self
Replaces every element in
self, starting atstart, with the givenvalue.DEPRECATED Use
#fill(value, start..)instead -
#fill(value : T, *, from start : Int, count : Int) : self
Replacescount or less (if there aren't enough) elements starting at the givenstart index withvalue.
DEPRECATED Use
#fill(value, start, count)instead -
#first(n : Int) : Array(T)
Returns the firstn elements of the array.
-
#flatten
Returns a new
Arraythat is a one-dimensional flattening ofself(recursively). -
#index(object, offset : Int = 0)
Returns the index of the first appearance ofobject in
selfstarting from the givenoffset, ornilifobject is not inself. -
#insert(index : Int, object : T) : self
Insertobject before the element atindex and shifting successive elements, if any.
-
#insert_all(index : Int, other : Indexable) : self
Inserts all of the elements fromother before the element atindex.
-
#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 lastn 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 lastn values from
self, at indexsize - 1. -
#pop : T
Removes the last value from
self, at indexsize - 1. -
#pop(&)
Removes the last value from
self. -
#pop? : T | Nil
Like
#pop, but returnsnilifselfis empty. - #pretty_print(pp) : Nil
-
#product(ary : Array(U)) forall U
Returns an
Arrayof all ordered combinations of elements taken from each ofselfandary asTuples.DEPRECATED Use
Indexable#cartesian_product(*others : Indexable)instead -
#product(enumerable : Enumerable, &)
Yields each ordered combination of the elements taken from each of
selfandenumerable as aTuple.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 whichpattern === element. - #remaining_capacity : Int32
- #repeated_permutations(size : Int = self.size) : Array(Array(T))
-
#replace(other : Array) : self
Replaces the contents of
selfwith the contents ofother. -
#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
ntimes. -
#rotate!(n : Int = 1) : self
Shifts all elements of
selfto the leftn 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 whichpattern === element. -
#shift(n : Int) : Array(T)
Removes the firstn 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 | Nil = nil) : Array(T)
Returns a new instance with all elements in the collection randomized.
-
#size : Int32
Returns the number of elements in the array.
-
#skip(count : Int) : Array(T)
Returns an
Arraywith the firstcount 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#<=>(seeComparable#<=>), 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
selfbased on the return value of the comparison methodT#<=>(seeComparable#<=>), using a stable sort algorithm. -
#sort!(&block : T, T -> U) : self forall U
Sorts all elements in
selfbased 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
selfby the output value of the block. -
#to_a : self
Returns an
Arraywith 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 toio.
-
#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
selfis an array of arrays and transposes the rows and columns. -
#truncate(start : Int, count : Int) : self
Removes all elements except thecount or less (if there aren't enough) elements starting at the givenstart index.
-
#truncate(range : Range) : self
Removes all elements except those within the givenrange.
-
#uniq : Array(T)
Returns a new
Arrayby removing duplicate values inself. -
#uniq(& : T -> ) : Array(T)
Returns a new
Arrayby removing duplicate values inself, 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 givenindex, without doing any bounds check.
-
#unsafe_put(index : Int, value : T)
Sets the element at the givenindex tovalue, 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#<=>(seeComparable#<=>), 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
selfbased on the return value of the comparison methodT#<=>(seeComparable#<=>), using an unstable sort algorithm. -
#unstable_sort!(&block : T, T -> U) : self forall U
Sorts all elements in
selfbased 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
selfby the output value of the block.
Instance methods inherited from module Comparable(Array(T))
<(other : T) : Bool
<,
<=(other : T)
<=,
<=>(other : T)
<=>,
==(other : T)
==,
>(other : T) : Bool
>,
>=(other : T)
>=,
clamp(min, max)clamp(range : Range) clamp
Instance methods inherited from module Indexable::Mutable(T)
[]=(index : Int, value : T) : T
[]=,
fill(value : T, start : Int, count : Int) : selffill(value : T, range : Range) : self
fill(value : T) : self
fill(start : Int, count : Int, & : Int32 -> T) : self
fill(range : Range, & : Int32 -> T) : self
fill(*, offset : Int = 0, & : Int32 -> T) : self fill, map!(& : T -> _) : self map!, map_with_index!(offset = 0, & : T, Int32 -> _) : self map_with_index!, reverse! : self reverse!, rotate!(n : Int = 1) : self rotate!, shuffle!(random : Random | Nil = nil) : self shuffle!, sort! : self
sort!(&block : T, T -> U) : self forall U sort!, sort_by!(&block : T -> _) : self sort_by!, swap(index0 : Int, index1 : Int) : self swap, unsafe_put(index : Int, value : T) unsafe_put, unstable_sort! : self
unstable_sort!(&block : T, T -> U) : self forall U unstable_sort!, unstable_sort_by!(&block : T -> _) : self unstable_sort_by!, update(index : Int, & : T -> _) : T update
Instance methods inherited from module Indexable(T)
[](index : Int)
[],
[]?(index : Int)
[]?,
bsearch(& : T -> _)
bsearch,
bsearch_index(& : T, Int32 -> _)
bsearch_index,
cartesian_product(*others : Indexable)
cartesian_product,
combinations(size : Int = self.size)
combinations,
dig(index : Int, *subindexes)
dig,
dig?(index : Int, *subindexes)
dig?,
each(& : T -> )each
each(*, start : Int, count : Int, & : T -> )
each(*, within range : Range, & : T -> ) each, each_cartesian(*others : Indexable, &)
each_cartesian(*others : Indexable) each_cartesian, each_combination(size : Int = self.size, reuse = false, &) : Nil
each_combination(size : Int = self.size, reuse = false) each_combination, each_index(& : Int32 -> ) : Nil
each_index
each_index(*, start : Int, count : Int, &) each_index, each_permutation(size : Int = self.size, reuse = false, &) : Nil
each_permutation(size : Int = self.size, reuse = false) each_permutation, each_repeated_combination(size : Int = self.size, reuse = false, &) : Nil
each_repeated_combination(size : Int = self.size, reuse = false) each_repeated_combination, empty? : Bool empty?, equals?(other : Indexable, &) : Bool
equals?(other, &) equals?, fetch(index : Int, &)
fetch(index, default) fetch, find(if_none, _offset offset : Int, & : T -> )
find(if_none = nil, *, offset : Int, & : T -> ) find, find!(offset : Int = 0, & : T -> ) find!, first(&) first, hash(hasher) hash, index(object, offset : Int = 0)
index(offset : Int = 0, & : T -> ) index, index!(obj, offset : Int = 0)
index!(offset : Int = 0, & : T -> ) index!, join(separator : String | Char | Number = "") : String join, last : T
last(&) last, last? : T | Nil last?, permutations(size : Int = self.size) : Array(Array(T)) permutations, repeated_combinations(size : Int = self.size) : Array(Array(T)) repeated_combinations, reverse_each(& : T -> ) : Nil
reverse_each reverse_each, rindex(value, offset = size - 1)
rindex(offset = size - 1, & : T -> ) rindex, rindex!(value, offset = size - 1)
rindex!(offset = size - 1, & : T -> ) rindex!, sample(n : Int, random : Random | Nil = nil) : Array(T)
sample(random : Random | Nil = nil) sample, size size, to_a(& : T -> U) : Array(U) forall U to_a, unsafe_fetch(index : Int) unsafe_fetch, values_at(*indexes : Int) values_at
Class methods inherited from module Indexable(T)
cartesian_product(indexables : Indexable(Indexable))
cartesian_product,
each_cartesian(indexables : Indexable(Indexable), reuse = false, &)each_cartesian(indexables : Indexable(Indexable), reuse = false) each_cartesian
Instance methods inherited from module Enumerable(T)
accumulate(initial : U) : Array(U) forall Uaccumulate : Array(T)
accumulate(initial : U, &block : U, T -> U) : Array(U) forall U
accumulate(&block : T, T -> T) : Array(T) accumulate, all?(& : T -> ) : Bool
all?(pattern) : Bool
all? : Bool all?, any?(& : T -> ) : Bool
any?(pattern) : Bool
any? : Bool any?, chunks(&block : T -> U) forall U chunks, compact_map(& : T -> _) compact_map, count(& : T -> ) : Int32
count(item) : Int32 count, cycle(n, & : T -> ) : Nil
cycle(& : T -> ) : Nil cycle, each(& : T -> ) each, each_cons(count : Int, reuse = false, &) each_cons, each_cons_pair(& : T, T -> ) : Nil each_cons_pair, each_slice(count : Int, reuse = false, &) each_slice, each_step(n : Int, *, offset : Int = 0, & : T -> ) : Nil each_step, each_with_index(offset = 0, &) each_with_index, each_with_object(obj : U, & : T, U -> ) : U forall U each_with_object, empty? : Bool empty?, find(if_none = nil, & : T -> ) find, find!(& : T -> ) : T find!, find_value(if_none = nil, & : T -> ) find_value, first(&)
first(count : Int) : Array(T)
first : T first, first? : T | Nil first?, flat_map(& : T -> _) flat_map, group_by(& : T -> U) forall U group_by, in_groups_of(size : Int, filled_up_with : U = nil) forall U
in_groups_of(size : Int, filled_up_with : U = nil, reuse = false, &) forall U in_groups_of, in_slices_of(size : Int) : Array(Array(T)) in_slices_of, includes?(obj) : Bool includes?, index(& : T -> ) : Int32 | Nil
index(obj) : Int32 | Nil index, index!(& : T -> ) : Int32
index!(obj) : Int32 index!, index_by(& : T -> U) : Hash(U, T) forall U index_by, join(io : IO, separator = "") : Nil
join(separator, io : IO) : Nil
join(separator = "") : String
join(io : IO, separator = "", & : T, IO -> )
join(separator, io : IO, &)
join(separator = "", & : T -> ) join, map(& : T -> U) : Array(U) forall U map, map_with_index(offset = 0, & : T, Int32 -> U) : Array(U) forall U map_with_index, max(count : Int) : Array(T)
max : T max, max? : T | Nil max?, max_by(& : T -> U) : T forall U max_by, max_by?(& : T -> U) : T | Nil forall U max_by?, max_of(& : T -> U) : U forall U max_of, max_of?(& : T -> U) : U | Nil forall U max_of?, min(count : Int) : Array(T)
min : T min, min? : T | Nil min?, min_by(& : T -> U) : T forall U min_by, min_by?(& : T -> U) : T | Nil forall U min_by?, min_of(& : T -> U) : U forall U min_of, min_of?(& : T -> U) : U | Nil forall U min_of?, minmax : Tuple(T, T) minmax, minmax? : Tuple(T | Nil, T | Nil) minmax?, minmax_by(& : T -> U) : Tuple(T, T) forall U minmax_by, minmax_by?(& : T -> U) : Tuple(T, T) | Tuple(Nil, Nil) forall U minmax_by?, minmax_of(& : T -> U) : Tuple(U, U) forall U minmax_of, minmax_of?(& : T -> U) : Tuple(U, U) | Tuple(Nil, Nil) forall U minmax_of?, none?(& : T -> ) : Bool
none?(pattern) : Bool
none? : Bool none?, one?(& : T -> ) : Bool
one?(pattern) : Bool
one? : Bool one?, partition(& : T -> ) : Tuple(Array(T), Array(T))
partition(type : U.class) forall U partition, present? : Bool present?, product(initial : Number)
product
product(initial : Number, & : T -> )
product(& : T -> _) product, reduce(memo, &)
reduce(&) reduce, reduce?(&) reduce?, reject(& : T -> )
reject(type : U.class) forall U
reject(pattern) : Array(T) reject, sample(n : Int, random : Random | Nil = nil) : Array(T)
sample(random : Random | Nil = nil) : T sample, select(& : T -> )
select(type : U.class) : Array(U) forall U
select(pattern) : Array(T) select, size : Int32 size, skip(count : Int) skip, skip_while(& : T -> ) : Array(T) skip_while, sum(initial)
sum
sum(initial, & : T -> )
sum(& : T -> ) sum, take_while(& : T -> ) : Array(T) take_while, tally(hash)
tally : Hash(T, Int32) tally, tally_by(hash, &)
tally_by(&block : T -> U) : Hash(U, Int32) forall U tally_by, to_a : Array(T)
to_a(& : T -> U) : Array(U) forall U to_a, to_h
to_h(& : T -> Tuple(K, V)) forall K, V to_h, to_set : Set(T)
to_set(&block : T -> U) : Set(U) forall U to_set, zip(*others : Indexable | Iterable | Iterator, &)
zip(*others : Indexable | Iterable | Iterator) zip, zip?(*others : Indexable | Iterable | Iterator, &)
zip?(*others : Indexable | Iterable | Iterator) zip?
Class methods inherited from module Enumerable(T)
element_type(x)
element_type
Instance methods inherited from module Iterable(T)
chunk(reuse = false, &block : T -> U) forall U
chunk,
chunk_while(reuse : Bool | Array(T) = false, &block : T, T -> B) forall B
chunk_while,
cycle(n)cycle cycle, each each, each_cons(count : Int, reuse = false) each_cons, each_cons_pair each_cons_pair, each_slice(count : Int, reuse = false) each_slice, each_step(n : Int)
each_step(n : Int, *, offset : Int) each_step, each_with_index(offset = 0) each_with_index, each_with_object(obj) each_with_object, slice_after(reuse : Bool | Array(T) = false, &block : T -> B) forall B
slice_after(pattern, reuse : Bool | Array(T) = false) slice_after, slice_before(reuse : Bool | Array(T) = false, &block : T -> B) forall B
slice_before(pattern, reuse : Bool | Array(T) = false) slice_before, slice_when(reuse : Bool | Array(T) = false, &block : T, T -> B) forall B slice_when
Instance methods inherited from class Reference
==(other : self)==(other : JSON::Any)
==(other : YAML::Any)
==(other) ==, dup dup, hash(hasher) hash, initialize initialize, inspect(io : IO) : Nil inspect, object_id : UInt64 object_id, pretty_print(pp) : Nil pretty_print, same?(other : Reference) : Bool
same?(other : Nil) same?, to_s(io : IO) : Nil to_s
Constructor methods inherited from class Reference
new
new,
unsafe_construct(address : Pointer, *args, **opts) : self
unsafe_construct
Class methods inherited from class Reference
pre_initialize(address : Pointer)
pre_initialize
Instance methods inherited from class Object
! : Bool
!,
!=(other)
!=,
!~(other)
!~,
==(other)
==,
===(other : JSON::Any)===(other : YAML::Any)
===(other) ===, =~(other) =~, as(type : Class) as, as?(type : Class) as?, class class, dup dup, hash(hasher)
hash hash, in?(collection : Object) : Bool
in?(*values : Object) : Bool in?, inspect(io : IO) : Nil
inspect : String inspect, is_a?(type : Class) : Bool is_a?, itself itself, nil? : Bool nil?, not_nil!(message)
not_nil! not_nil!, pretty_inspect(width = 79, newline = "\n", indent = 0) : String pretty_inspect, pretty_print(pp : PrettyPrint) : Nil pretty_print, responds_to?(name : Symbol) : Bool responds_to?, tap(&) tap, to_json(io : IO) : Nil
to_json : String to_json, to_pretty_json(indent : String = " ") : String
to_pretty_json(io : IO, indent : String = " ") : Nil to_pretty_json, to_s(io : IO) : Nil
to_s : String to_s, to_yaml(io : IO) : Nil
to_yaml : String to_yaml, try(&) try, unsafe_as(type : T.class) forall T unsafe_as
Class methods inherited from class Object
from_json(string_or_io : String | IO, root : String)from_json(string_or_io : String | IO) from_json, from_yaml(string_or_io : String | IO) from_yaml
Macros inherited from class Object
class_getter(*names, &block)
class_getter,
class_getter!(*names)
class_getter!,
class_getter?(*names, &block)
class_getter?,
class_property(*names, &block)
class_property,
class_property!(*names)
class_property!,
class_property?(*names, &block)
class_property?,
class_setter(*names)
class_setter,
def_clone
def_clone,
def_equals(*fields)
def_equals,
def_equals_and_hash(*fields)
def_equals_and_hash,
def_hash(*fields)
def_hash,
delegate(*methods, to object)
delegate,
forward_missing_to(delegate)
forward_missing_to,
getter(*names, &block)
getter,
getter!(*names)
getter!,
getter?(*names, &block)
getter?,
property(*names, &block)
property,
property!(*names)
property!,
property?(*names, &block)
property?,
setter(*names)
setter
Constructor Detail
Returns the additive identity of this type.
This is an empty array.
Creates a newArray, allocating an internal buffer with the givencapacity,
and yielding that buffer. The given block must return the desired size of the array.
This method isunsafe, 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
Creates a newArray of the givensize filled with the samevalue 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 thesame 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.
Creates a new emptyArray backed by a buffer that is initially
initial_capacity big.
Theinitial_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
Creates a newArray of the givensize and invokes the given block once
for each index ofself, 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]]
Class Method Detail
Yields each ordered combination of the elements taken from each of the
arrays asArrays.
Traversal of elements starts from the last given array.
DEPRECATED UseIndexable.each_cartesian(indexables : Indexable(Indexable), reuse = false, &block) instead
Yields each ordered combination of the elements taken from each of the
arrays asArrays.
Traversal of elements starts from the last given array.
DEPRECATED UseIndexable.each_cartesian(indexables : Indexable(Indexable), reuse = false, &block) instead
Parses aString orIO 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 anArray, use the block-less overload.
Returns anArray of all ordered combinations of elements taken from each
of thearrays asArrays.
Traversal of elements starts from the last given array.
DEPRECATED UseIndexable.cartesian_product(indexables : Indexable(Indexable)) instead
Returns anArray of all ordered combinations of elements taken from each
of thearrays asArrays.
Traversal of elements starts from the last given array.
DEPRECATED UseIndexable.cartesian_product(indexables : Indexable(Indexable)) instead
Instance Method Detail
Set intersection: returns a newArray containing elements common toself
andother, excluding any duplicates. The order is preserved fromself.
[1, 1, 3, 5] & [1, 2, 3] # => [ 1, 3 ]
['a', 'b', 'b', 'z'] & ['a', 'b', 'c'] # => [ 'a', 'b' ]
See also:#uniq.
Repetition: Returns a newArray built by concatenatingtimes copies ofself.
["a", "b", "c"] * 2 # => [ "a", "b", "c", "a", "b", "c" ]
Concatenation. Returns a newArray built by concatenatingself andother.
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]
Difference. Returns a newArray that is a copy ofself, removing any items
that appear inother. The order ofself is preserved.
[1, 2, 3] - [2, 1] # => [3]
Combined comparison operator.
Returns-1,0 or1 depending on whetherself is less thanother, equalsother
or is greater thanother.
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
Equality. Returnstrue if each element inself is equal to each
corresponding element inother.
ary = [1, 2, 3]
ary == [1, 2, 3] # => true
ary == [2, 3] # => false
Returns count or less (if there aren't enough) elements starting at the given start index.
Negativestart is added toself.size, thus it's treated as
index counting from the end of the array,-1 designating the last element.
RaisesIndexError ifstart index is out of bounds.
RaisesArgumentError ifcount 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
Returns all elements that are within the given range.
The first element in the returned array isself[range.begin] followed
by the next elements up to indexrange.end (orself[range.end - 1] if
the range is exclusive).
If there are fewer elements inself, 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 toself.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"]
RaisesIndexError if the start index is out of range (range.begin > self.size || range.begin < -self.size). Ifrange.begin == self.size an
empty array is returned. Ifrange.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] # => []
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]
Replaces a subrange with a single value. All elements in the range
start...start+count are removed and replaced by a single element
value.
Ifcount is zero,value is inserted atstart.
Negative values ofstart 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]
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]
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]
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]
DEPRECATED Use#[]=(start, count, values) instead
Replaces a subrange with a single value. All elements in the range
start...start+count are removed and replaced by a single element
value.
Ifcount is zero,value is inserted atstart.
Negative values ofstart 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]
DEPRECATED Use#[]=(start, count, value) instead
Like#[](Range), but returnsnil ifrange.begin is out of range.
a = ["a", "b", "c", "d", "e"]
a[6..10]? # => nil
a[6..]? # => nil
Set union: returns a newArray by joiningself withother, excluding
any duplicates, and preserving the order fromself.
["a", "b", "c"] | ["c", "d", "a"] # => [ "a", "b", "c", "d" ]
See also:#uniq.
Returns a newArray that hasself's elements cloned.
That is, it returns a deep copy ofself.
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]]
Returns a copy ofself with allnil elements removed.
["a", nil, "b", nil, "c", nil].compact # => ["a", "b", "c"]
Removes allnil elements fromself and returnsself.
ary = ["a", nil, "b", nil, "c"]
ary.compact!
ary # => ["a", "b", "c"]
Appends the elements ofother toself, and returnsself.
ary = ["a", "b"]
ary.concat(["c", "d"])
ary # => ["a", "b", "c", "d"]
Appends the elements ofother toself, and returnsself.
ary = ["a", "b"]
ary.concat(["c", "d"])
ary # => ["a", "b", "c", "d"]
Removes all items fromself that are equal toobj.
Returns the last found element that was equal toobj,
if any, ornil if not found.
a = ["a", "b", "b", "b", "c"]
a.delete("b") # => "b"
a # => ["a", "c"]
a.delete("x") # => nil
a # => ["a", "c"]
Removescount elements fromself starting atstart.
If the size ofself is less thancount, removes values to the end of the array without error.
Returns an array of the removed elements with the original order ofself preserved.
RaisesIndexError ifstart 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
Removes the element atindex, returning that element.
RaisesIndexError ifindex is out of range.
a = ["ant", "bat", "cat", "dog"]
a.delete_at(2) # => "cat"
a # => ["ant", "bat", "dog"]
a.delete_at(99) # raises IndexError
Removes all elements within the givenrange.
Returns an array of the removed elements with the original order ofself preserved.
RaisesIndexError 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
Removescount elements fromself starting atstart.
If the size ofself is less thancount, removes values to the end of the array without error.
Returns an array of the removed elements with the original order ofself preserved.
RaisesIndexError ifstart 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
DEPRECATED Use#delete_at(start, count) instead
Returns a newArray that has exactlyself's elements.
That is, it returns a shallow copy ofself.
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]]
Yields each index ofself, starting atstart, to the given block and then assigns
the block's value in that position. Returnsself.
Negative values ofstart count from the end of the array.
RaisesIndexError ifstart is outside the array range.
a = [1, 2, 3, 4]
a.fill(2) { |i| i * i } # => [1, 2, 4, 9]
DEPRECATED Use#fill(start.., &) instead
Yields each index ofself, starting atstart, to the given block and then assigns
the block's value in that position. Returnsself.
Negative values ofstart count from the end of the array.
RaisesIndexError ifstart is outside the array range.
a = [1, 2, 3, 4]
a.fill(2) { |i| i * i } # => [1, 2, 4, 9]
DEPRECATED Use#fill(start.., &) instead
Yields each index ofself, starting atstart and justcount times,
to the given block and then assigns the block's value in that position. Returnsself.
Negative values ofstart count from the end of the array.
RaisesIndexError ifstart is outside the array range.
Has no effect ifcount is zero or negative.
a = [1, 2, 3, 4, 5, 6]
a.fill(2, 2) { |i| i * i } # => [1, 2, 4, 9, 5, 6]
DEPRECATED UseIndexable::Mutable#fill(start, count, &) instead
Replacescount or less (if there aren't enough) elements starting at the
givenstart index withvalue. Returnsself.
Negative values ofstart count from the end of the container.
RaisesIndexError if thestart index is out of range.
RaisesArgumentError ifcount is negative.
array = [1, 2, 3, 4, 5]
array.fill(9, 2, 2) # => [1, 2, 9, 9, 5]
array # => [1, 2, 9, 9, 5]
Replaces every element inself, starting atstart, with the givenvalue. Returnsself.
Negative values ofstart count from the end of the array.
a = [1, 2, 3, 4, 5]
a.fill(9, 2) # => [1, 2, 9, 9, 9]
DEPRECATED Use#fill(value, start..) instead
Replaces every element inrange withvalue. Returnsself.
Negative values offrom count from the end of the array.
a = [1, 2, 3, 4, 5]
a.fill(9, 2..3) # => [1, 2, 9, 9, 5]
Replaces every element inself with the givenvalue. Returnsself.
array = [1, 2, 3, 4]
array.fill(2) # => [2, 2, 2, 2]
array # => [2, 2, 2, 2]
Replaces every element inself, starting atstart, with the givenvalue. Returnsself.
Negative values ofstart count from the end of the array.
a = [1, 2, 3, 4, 5]
a.fill(9, 2) # => [1, 2, 9, 9, 9]
DEPRECATED Use#fill(value, start..) instead
Replacescount or less (if there aren't enough) elements starting at the
givenstart index withvalue. Returnsself.
Negative values ofstart count from the end of the container.
RaisesIndexError if thestart index is out of range.
RaisesArgumentError ifcount is negative.
array = [1, 2, 3, 4, 5]
array.fill(9, 2, 2) # => [1, 2, 9, 9, 5]
array # => [1, 2, 9, 9, 5]
DEPRECATED Use#fill(value, start, count) instead
Returns the firstn elements of the array.
[1, 2, 3].first(2) # => [1, 2]
[1, 2, 3].first(4) # => [1, 2, 3]
Returns a newArray that is a one-dimensional flattening ofself (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]
Returns the index of the first appearance ofobject inself
starting from the givenoffset, ornil ifobject is not inself.
[1, 2, 3, 1, 2, 3].index(2, offset: 2) # => 4
Insertobject before the element atindex and shifting successive elements, if any.
Returnsself.
Negative values ofindex 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"]
Inserts all of the elements fromother before the element atindex.
This method shifts the element currently atindex (if any) and any
subsequent elements to the right, increasing their indices. If the value
ofindex is negative, counting starts from the end of the array.
For example,-1 indicates insertion after the last element,-2 before
the last element.
RaisesIndexError if theindex 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
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>
Returns the lastn elements of the array.
[1, 2, 3].last(2) # => [2, 3]
[1, 2, 3].last(4) # => [1, 2, 3]
Optimized version ofEnumerable#map_with_index.
Accepts an optionaloffset 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"]
Removes the lastn values fromself, at indexsize - 1.
This method returns an array of the removed values, with the original order preserved.
Ifn is greater than the size ofself, all values will be removed fromself
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.
Removes the last value fromself, at indexsize - 1.
This method returns the removed value.
RaisesIndexError if array is of 0 size.
a = ["a", "b", "c"]
a.pop # => "c"
a # => ["a", "b"]
See also:#truncate.
Removes the last value fromself.
If the array is empty, the given block is called.
a = [1]
a.pop { "Testing" } # => 1
a.pop { "Testing" } # => "Testing"
See also:#truncate.
Returns anArray of all ordered combinations of elements taken from each
ofself andary asTuples.
Traversal of elements starts fromary.
DEPRECATED UseIndexable#cartesian_product(*others : Indexable) instead
Yields each ordered combination of the elements taken from each ofself
andenumerable as aTuple.
Traversal of elements starts fromenumerable.
DEPRECATED UseIndexable#each_cartesian(*others : Indexable, &block) instead
Append. Pushes one value to the end ofself, given that the type of the value isT
(which might be a single type or a union of types).
This method returnsself, 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]
Append multiple values. The same as#push, but takes an arbitrary number
of values to push intoself. Returnsself.
a = ["a"]
a.push("b", "c") # => ["a", "b", "c"]
Modifiesself, deleting the elements in the collection for which the
passed block is truthy. Returnsself.
ary = [1, 6, 2, 4, 8]
ary.reject! { |x| x > 3 }
ary # => [1, 2]
See also:Array#reject.
Modifiesself, 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!.
Replaces the contents ofself with the contents ofother.
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]
Returns an array with all the elements in the collection reversed.
a = [1, 2, 3]
a.reverse # => [3, 2, 1]
Returns an array with all the elements shifted to the leftn 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]
Shifts all elements ofself to the leftn times. Returnsself.
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]
Modifiesself, keeping only the elements in the collection for which the
passed block is truthy. Returnsself.
ary = [1, 6, 2, 4, 8]
ary.select! { |x| x > 3 }
ary # => [6, 4, 8]
See also:Array#select.
Modifiesself, 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!.
Removes the firstn values ofself, starting at index 0.
This method returns an array of the removed values.
Ifn is greater than the size ofself, all values will be removed fromself
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.
Removes the first value ofself, at index 0. This method returns the removed value.
If the array is empty, it raisesIndexError.
a = ["a", "b", "c"]
a.shift # => "a"
a # => ["b", "c"]
See also:#truncate.
Removes the first value ofself, 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.
Removes the first value ofself, at index 0. This method returns the removed value.
If the array is empty, it returnsnil without raising any error.
a = ["a", "b"]
a.shift? # => "a"
a # => ["b"]
a.shift? # => "b"
a # => []
a.shift? # => nil
a # => []
See also:#truncate.
Returns a new instance with all elements in the collection randomized.
SeeIndexable::Mutable#shuffle! for details.
Returns anArray with the firstcount elements removed
from the original array.
Ifcount 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]
Returns a new instance with all elements sorted based on the return value of
their comparison methodT#<=> (seeComparable#<=>), using a stable sort algorithm.
a = [3, 1, 2]
a.sort # => [1, 2, 3]
a # => [3, 1, 2]
SeeIndexable::Mutable#sort! for details on the sorting mechanism.
RaisesArgumentError if the comparison between any two elements returnsnil.
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]
SeeIndexable::Mutable#sort!(&block : T, T -> U) for details on the sorting mechanism.
RaisesArgumentError if for any two elements the block returnsnil.
Sorts all elements inself based on the return value of the comparison
methodT#<=> (seeComparable#<=>), using a stable sort algorithm.
a = [3, 1, 2]
a.sort!
a # => [1, 2, 3]
This sort operation modifiesself. See#sort for a non-modifying option
that allocates a new instance.
SeeSlice#sort! for details on the implementation.
RaisesArgumentError if the comparison between any two elements returnsnil.
Sorts all elements inself based on the comparator in the given block, using
a stable sort algorithm.
The block must implement a comparison between two elementsa andb,
wherea < b returns-1,a == b returns0, anda > b returns1.
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 modifiesself. See#sort(&block : T, T -> U) for a
non-modifying option that allocates a new instance.
SeeSlice#sort!(&block : T, T -> U) for details on the implementation.
RaisesArgumentError if for any two elements the block returnsnil.
Returns a new instance with all elements sorted by the output value of the
block. The output values are compared via the comparison methodT#<=>
(seeComparable#<=>), 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.
SeeIndexable::Mutable#sort_by!(&block : T -> _) for details on the sorting mechanism.
RaisesArgumentError if the comparison between any two comparison values returnsnil.
Sorts all elements inself by the output value of the
block. The output values are compared via the comparison method#<=>
(seeComparable#<=>), using a stable sort algorithm.
a = %w(apple pear fig)
a.sort_by! { |word| word.size }
a # => ["fig", "pear", "apple"]
This sort operation modifiesself. 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.
RaisesArgumentError if the comparison between any two comparison values returnsnil.
Returns anArray with all the elements in the collection.
(1..5).to_a # => [1, 2, 3, 4, 5]
Prints a nicely readable and concise string representation of this array toio.
The result resembles an array literal but it does not necessarily compile.
Each element is presented using its#inspect(io) result to avoid ambiguity.
Returns a pointer to the internal buffer whereself's elements are stored.
This method isunsafe because it returns a pointer, and the pointed might eventually
not be that ofself if the array grows and its internal buffer is reallocated.
ary = [1, 2, 3]
ary.to_unsafe[0] # => 1
Assumes thatself 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]]
Removes all elements except thecount or less (if there aren't enough)
elements starting at the givenstart index. Returnsself.
Negative values ofstart count from the end of the array.
RaisesIndexError if thestart index is out of range.
RaisesArgumentError ifcount is negative.
a = [0, 1, 4, 9, 16, 25]
a.truncate(2, 3) # => [4, 9, 16]
a # => [4, 9, 16]
Removes all elements except those within the givenrange. Returnsself.
a = [0, 1, 4, 9, 16, 25]
a.truncate(1..-3) # => [1, 4, 9]
a # => [1, 4, 9]
Returns a newArray by removing duplicate values inself.
a = ["a", "a", "b", "b", "c"]
a.uniq # => ["a", "b", "c"]
a # => [ "a", "a", "b", "b", "c" ]
Returns a newArray by removing duplicate values inself, 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"}]
Removes duplicate elements fromself. Returnsself.
a = ["a", "a", "b", "b", "c"]
a.uniq! # => ["a", "b", "c"]
a # => ["a", "b", "c"]
Removes duplicate elements fromself, using the block's value for comparison. Returnsself.
a = [{"student", "sam"}, {"student", "george"}, {"teacher", "matz"}]
a.uniq! { |s| s[0] } # => [{"student", "sam"}, {"teacher", "matz"}]
a # => [{"student", "sam"}, {"teacher", "matz"}]
Returns the element at the givenindex, without doing any bounds check.
Indexable makes sure to invoke this method withindex in0...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.
Sets the element at the givenindex tovalue, without doing any bounds check.
Indexable::Mutable makes sure to invoke this method withindex 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.
Prepend. Addsobject to the beginning ofself, given that the type of the value isT
(which might be a single type or a union of types).
This method returnsself, 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"]
Prepend multiple values. The same as#unshift, but takes an arbitrary number
of values to add to the array. Returnsself.
Returns a new instance with all elements sorted based on the return value of
their comparison methodT#<=> (seeComparable#<=>), using an unstable sort algorithm.
a = [3, 1, 2]
a.unstable_sort # => [1, 2, 3]
a # => [3, 1, 2]
SeeIndexable::Mutable#unstable_sort! for details on the sorting mechanism.
RaisesArgumentError if the comparison between any two elements returnsnil.
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]
SeeIndexable::Mutable#unstable_sort!(&block : T, T -> U) for details on the sorting mechanism.
RaisesArgumentError if for any two elements the block returnsnil.
Sorts all elements inself based on the return value of the comparison
methodT#<=> (seeComparable#<=>), using an unstable sort algorithm.
a = [3, 1, 2]
a.unstable_sort!
a # => [1, 2, 3]
This sort operation modifiesself. See#unstable_sort for a non-modifying
option that allocates a new instance.
SeeSlice#unstable_sort! for details on the implementation.
RaisesArgumentError if the comparison between any two elements returnsnil.
Sorts all elements inself based on the comparator in the given block,
using an unstable sort algorithm.
The block must implement a comparison between two elementsa andb,
wherea < b returns-1,a == b returns0, anda > b returns1.
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 modifiesself. See#unstable_sort(&block : T, T -> U)
for a non-modifying option that allocates a new instance.
SeeSlice#unstable_sort!(&block : T, T -> U) for details on the implementation.
RaisesArgumentError if for any two elements the block returnsnil.
Returns a new instance with all elements sorted by the output value of the
block. The output values are compared via the comparison method#<=>
(seeComparable#<=>), 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.
SeeIndexable::Mutable#unstable_sort!(&block : T -> _) for details on the sorting mechanism.
RaisesArgumentError if the comparison between any two comparison values returnsnil.
Sorts all elements inself by the output value of the
block. The output values are compared via the comparison method#<=>
(seeComparable#<=>), using an unstable sort algorithm.
a = %w(apple pear fig)
a.unstable_sort_by! { |word| word.size }
a # => ["fig", "pear", "apple"]
This sort operation modifiesself. 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.
RaisesArgumentError if the comparison between any two comparison values returnsnil.