- README

- Top Level Namespace
- Adler32
- ArgumentError
- Array
- Atomic
- Base64
  - Error
- Benchmark
  - BM
    - Job
    - Tms
  - IPS
    - Entry
    - Job
- BigFloat
- BigInt
- BigRational
- BitArray
- Bool
- Box
- Bytes
- Channel
  - Buffered
  - ClosedError
  - ReceiveAction
  - SelectAction
  - SendAction
  - Unbuffered
- Char
  - Reader
- Class
- Colorize
  - Object
  - ObjectExtensions
- Comparable
- Complex
- Concurrent
  - CanceledError
- CRC32
- Crypto
  - Bcrypt
    - Error
    - Password
  - Blowfish
  - Subtle
- CSV
  - Builder
    - Row
  - Error
  - Lexer
  - MalformedCSVError
  - Parser
  - Row
  - Token
    - Kind
- Debug
  - DWARF
    - Abbrev
      - Attribute
    - AT
    - FORM
    - Info
      - Value
    - LineNumbers
      - Register
      - Row
      - Sequence
    - LNE
    - LNS
    - Strings
    - TAG
  - ELF
    - Endianness
    - Error
    - Ident
    - Klass
    - Machine
    - OSABI
    - SectionHeader
      - Flags
      - Type
    - Type
- Deque
- Digest
  - Base
  - MD5
  - SHA1
- Dir
- DivisionByZero
- DL
- ECR
- Enum
- Enumerable
  - EmptyError
- ENV
- Errno
- Exception
- Fiber
- File
  - Stat
- FileUtils
- Flate
  - Error
  - Reader
  - Strategy
  - Writer
- Float
  - Primitive
- Float32
- Float64
- GC
  - Stats
- Gzip
  - Error
  - Header
  - Reader
  - Writer
- Hash
- HTML
- HTTP
  - Client
    - BodyType
    - Response
  - CompressHandler
  - ComputedContentTypeHeader
  - Cookie
  - Cookies
  - ErrorHandler
  - FormData
    - Builder
    - Error
    - FileMetadata
    - Parser
    - Part
  - Handler
    - Proc
  - Headers
  - LogHandler
  - Multipart
    - Builder
    - Error
    - Parser
  - Params
    - Builder
  - Request
  - Server
    - Context
    - RequestProcessor
    - Response
  - StaticFileHandler
    - DirectoryListing
  - WebSocket
  - WebSocketHandler
- Indexable
- IndexError
- INI
- Int
  - Primitive
  - Signed
  - Unsigned
- Int16
- Int32
- Int64
- Int8
- InvalidByteSequenceError
- IO
  - Buffered
  - ByteFormat
    - BigEndian
    - LittleEndian
    - NetworkEndian
    - SystemEndian
  - Delimited
  - EncodingOptions
  - EOFError
  - Error
  - FileDescriptor
  - Hexdump
  - Memory
  - MultiWriter
  - Seek
  - Sized
  - Timeout
- IPSocket
- Iterable
- Iterator
  - IteratorWrapper
  - Stop
- JSON
  - Any
  - Builder
    - ArrayState
    - DocumentEndState
    - DocumentStartState
    - ObjectState
    - StartState
    - State
  - Error
  - Lexer
  - ParseException
  - Parser
  - PullParser
  - Token
  - Type
- KeyError
- Levenshtein
  - Finder
- LLVM
  - ABI
    - AArch64
    - ArgKind
    - ArgType
    - ARM
    - FunctionType
    - X86
    - X86_64
      - RegClass
  - AtomicOrdering
  - AtomicRMWBinOp
  - Attribute
  - AttributeIndex
  - BasicBlock
  - BasicBlockCollection
  - Builder
  - CallConvention
  - CodeGenFileType
  - CodeGenOptLevel
  - CodeModel
  - Context
  - DIBuilder
  - DIFlags
  - DwarfTag
  - DwarfTypeEncoding
  - Function
  - FunctionCollection
  - FunctionPassManager
    - Runner
  - GenericValue
  - GlobalCollection
  - InstructionCollection
  - IntPredicate
  - JITCompiler
  - Linkage
  - MemoryBuffer
  - Module
  - ModuleFlag
  - ModulePassManager
  - ParameterCollection
  - PassManagerBuilder
  - PassRegistry
  - PhiTable
  - RealPredicate
  - RelocMode
  - Target
  - TargetData
  - TargetMachine
  - Type
    - Kind
  - Value
    - Kind
  - ValueMethods
  - VerifierFailureAction
- Logger
  - Formatter
  - Severity
- Markdown
  - HTMLRenderer
  - Parser
    - PrefixHeader
    - UnorderedList
  - Renderer
- Math
- Mutex
- NamedTuple
- Nil
- Number
  - Primitive
- OAuth
  - AccessToken
  - Consumer
  - Error
  - RequestToken
- OAuth2
  - AccessToken
    - Bearer
    - Mac
  - Client
  - Error
  - Session
- Object
- OpenSSL
  - Digest
    - Error
    - UnsupportedError
  - DigestBase
  - Error
  - HMAC
  - MD5
  - SHA1
  - SSL
    - Context
      - Client
      - Server
    - Error
    - ErrorType
    - Modes
    - Options
    - Socket
      - Client
      - Server
    - VerifyMode
    - X509VerifyFlags
- OptionParser
  - Exception
  - InvalidOption
  - MissingOption
- PartialComparable
- Pointer
  - Appender
- PrettyPrint
- Proc
- Process
  - Env
  - Status
  - Stdio
  - Tms
- Random
  - MT19937
- Range
- Readline
  - CompletionProc
  - KeyBindingProc
- Reference
- Reflect
- Regex
  - MatchData
  - Options
- SecureRandom
- Set
- Signal
- Slice
- Socket
  - Address
  - Addrinfo
  - Error
  - Family
  - IPAddress
  - Protocol
  - Server
  - Type
  - UNIXAddress
- Spec
  - Expectations
  - Methods
  - ObjectExtensions
- StaticArray
- String
  - Builder
  - RawConverter
- StringPool
- StringScanner
- Struct
- Symbol
- System
- TCPServer
- TCPSocket
- Tempfile
- Termios
  - AttributeSelection
  - BaudRate
  - ControlMode
  - InputMode
  - LineControl
  - LocalMode
  - OutputMode
- Time
  - DayOfWeek
  - EpochConverter
  - EpochMillisConverter
  - Format
    - Error
  - Kind
  - MonthSpan
  - Span
- Tuple
- TypeCastError
- UDPSocket
- UInt16
- UInt32
- UInt64
- UInt8
- Unicode
  - CaseOptions
- Union
- UNIXServer
- UNIXSocket
- URI
  - Error
- Value
- WeakRef
- XML
  - Attributes
  - AttributeType
  - Builder
  - Error
  - HTMLParserOptions
  - Namespace
  - Node
  - NodeSet
  - ParserOptions
  - Reader
  - SaveOptions
  - Type
  - XPathContext
- YAML
  - Any
  - Builder
  - Error
  - EventKind
  - ParseException
  - Parser
  - PullParser
  - Type
- Zip
  - CompressionMethod
  - Error
  - File
    - Entry
  - FileInfo
  - Reader
    - Entry
  - Writer
    - Entry
- Zlib
  - Error
  - Reader
  - Writer

# class Array(T)

- Array(T)
- Reference
- Object

## Overview

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

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

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

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

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

When creating an empty array you must always specify T:

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

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

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

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

The above is the same as this:

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

## Included Modules

- Comparable(Array(T))
- Indexable(T)

## Defined in:

## Class Method Summary

- .build(capacity : Int, &block)

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

- .each_product(arrays : Array(Array), reuse = false, &block)
- .each_product(*arrays : Array, reuse = false, &block)
- .from_json(string_or_io, &block) : Nil

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

- .from_yaml(string_or_io, &block)
- .new(size : Int, value : T)

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

- .new(initial_capacity : Int)

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

- .new(pull : JSON::PullParser)
- .new(pull : YAML::PullParser)
- .new

  Creates a new empty Array.

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

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

- .new(pull : JSON::PullParser, &block)
- .new(pull : YAML::PullParser, &block)
- .product(arrays)
- .product(*arrays : Array)

## Instance Method Summary

- #&(other : Array(U)) forall U

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

- #*(times : Int)

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

- #+(other : Array(U)) forall U

  Concatenation.

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

  Difference.

- #<<(value : T)

  Append.

- #<=>(other : Array)

  Combined comparison operator.

- #==(other : Array)

  Equality.

- #[](range : Range(Int, Int))

  Returns all elements that are within the given range.

- #[](start : Int, count : Int)

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

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

  Replaces a subrange with the elements of the given array.

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

  Replaces a subrange with a single value.

- #[]=(index : Int, value : T)

  Sets the given value at the given index.

- #[]=(index : Int, count : Int, values : Array(T))

  Replaces a subrange with the elements of the given array.

- #[]=(index : Int, count : Int, value : T)

  Replaces a subrange with a single value.

- #clear

  Removes all elements from self.

- #clone

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

- #combinations(size : Int = self.size)
- #compact

  Returns a copy of `self` with all `nil` elements removed.

- #compact!

  Removes all `nil` elements from `self`.

- #concat(other : Enumerable)

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

- #concat(other : Array)

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

- #delete(obj)

  Removes all items from `self` that are equal to obj.

- #delete_at(index : Int, count : Int)

  Removes count elements from `self` starting at index.

- #delete_at(index : Int)

  Removes the element at index, returning that element.

- #delete_at(range : Range(Int, Int))

  Removes all elements within the given range.

- #dup

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

- #each_combination(size : Int = self.size, reuse = false)
- #each_combination(size : Int = self.size, reuse = false, &block) : Nil
- #each_permutation(size : Int = self.size, reuse = false)

  Returns an `Iterator` over each possible permutation of size of `self`.

- #each_permutation(size : Int = self.size, reuse = false, &block) : Nil

  Yields each possible permutation of size of `self`.

- #each_repeated_combination(size : Int = self.size, reuse = false, &block) : Nil
- #each_repeated_combination(size : Int = self.size, reuse = false)
- #each_repeated_permutation(size : Int = self.size, reuse = false, &block) : Nil
- #fill(from : Int, count : Int, &block)

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

- #fill(from : Int, &block)

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

- #fill(range : Range(Int, Int), &block)

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

- #fill(&block)

  Yields each index of `self` to the given block and then assigns the block's value in that position.

- #fill(value : T, from : Int, count : Int)

  Replaces every element in `self`, starting at from and only count times, with the given value.

- #fill(value : T, from : Int)

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

- #fill(value : T, range : Range(Int, Int))

  Replaces every element in range with value.

- #fill(value : T)

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

- #first(n : Int)

  Returns the first n elements of the array.

- #flatten

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

- #insert(index : Int, object : T)

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

- #last(n : Int)

  Returns the last n elements of the array.

- #map(&block : T -> U) forall U

  Optimized version of `Enumerable#map`.

- #map!(&block)

  Invokes the given block for each element of `self`, replacing the element with the value returned by the block.

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

  Optimized version of `Enumerable#map_with_index`.

- #permutations(size : Int = self.size)

  Returns an `Array` with all possible permutations of size.

- #pop(&block)

  Removes the last value from `self`.

- #pop

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

- #pop(n : Int)

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

- #pop?

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

- #pretty_print(pp) : Nil
- #product(enumerable : Enumerable, &block)
- #product(ary : Array(U)) forall U
- #push(*values : T)

  Append multiple values.

- #push(value : T)

  Append.

- #reject!(&block)

  Modifies `self`, deleting the elements in the collection for which the passed block returns `true`.

- #repeated_combinations(size : Int = self.size)
- #repeated_permutations(size : Int = self.size)
- #replace(other : Array)
- #reverse

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

- #reverse!

  Reverses in-place all the elements of `self`.

- #rotate(n = 1)
- #rotate!(n = 1)
- #sample(n : Int, random = Random::DEFAULT)

  Returns n number of random elements from `self`, using the given random number generator.

- #select!(&block)

  Modifies `self`, keeping only the elements in the collection for which the passed block returns `true`.

- #shift(n : Int)

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

- #shift

  Removes the first value of `self`, at index 0.

- #shift(&block)
- #shift?
- #shuffle(random = Random::DEFAULT)

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

- #shuffle!(random = Random::DEFAULT)

  Modifies `self` by randomizing the order of elements in the collection using the given random number generator.

- #size : Int32

  Returns the number of elements in the array.

- #sort

  Returns an array with all elements in the collection sorted.

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

  Modifies `self` by sorting the elements in the collection.

- #sort!(&block : T, T -> Int32)
- #sort_by(&block : T -> _)
- #sort_by!(&block : T -> _)
- #swap(index0, index1)
- #to_a
- #to_json(json : JSON::Builder)
- #to_s(io : IO)
- #to_unsafe : Pointer(T)

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

- #to_yaml(yaml : YAML::Builder)
- #transpose

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

- #uniq

  Returns a new `Array` by removing duplicate values in `self`.

- #uniq(&block : T -> _)

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

- #uniq!

  Removes duplicate elements from `self`.

- #uniq!(&block)

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

- #unsafe_at(index : Int)
- #unshift(obj : T)

  Prepend.

- #unshift(*values : T)

  Prepend multiple values.

- #update(index : Int, &block)
- #|(other : Array(U)) forall U

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

### Instance methods inherited from module `Comparable(Array(T))`

<(other : T) <, <=(other : T) <=, <=>(other : T) <=>, ==(other : T) ==, >(other : T) >, >=(other : T) >=

### Instance methods inherited from module `Indexable(T)`

[](index : Int) [], []?(index : Int) []?, at(index : Int, &block)
at(index : Int) at, bsearch(&block) bsearch, bsearch_index(&block) bsearch_index, each(&block)
each each, each_index(&block) : Nil
each_index each_index, empty? empty?, equals?(other : Indexable, &block)
equals?(other, &block) equals?, first(&block)
first first, first? first?, hash hash, index(object, offset : Int = 0)
index(offset : Int = 0, &block) index, last
last(&block) last, last? last?, reverse_each(&block) : Nil
reverse_each reverse_each, rindex(offset = size - 1, &block)
rindex(value, offset = size - 1) rindex, sample(random = Random::DEFAULT) sample, size size, unsafe_at(index : Int) unsafe_at, values_at(*indexes : Int) values_at, zip(other : Indexable, &block)
zip(other : Indexable(U)) forall U zip, zip?(other : Indexable, &block)
zip?(other : Indexable(U)) forall U zip?

### Instance methods inherited from module `Enumerable(T)`

all?(&block)
all? all?, any?(&block)
any? any?, chunks(&block : T -> U) forall U chunks, compact_map(&block) compact_map, count(&block)
count(item) count, cycle(n, &block)
cycle(&block) cycle, each(&block : T -> _) each, each_cons(count : Int, reuse = false, &block) each_cons, each_slice(count : Int, reuse = false, &block) each_slice, each_with_index(offset = 0, &block) each_with_index, each_with_object(obj, &block) each_with_object, find(if_none = nil, &block) find, first(count : Int)
first first, first? first?, flat_map(&block : T -> Array(U) | Iterator(U) | U) forall U flat_map, grep(pattern) grep, group_by(&block : 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, &block) forall U in_groups_of, includes?(obj) includes?, index(&block)
index(obj) index, index_by(&block : T -> U) forall U index_by, join(separator, io)
join(separator = "")
join(separator, io, &block)
join(separator = "", &block) join, map(&block : T -> U) forall U map, map_with_index(&block : T, Int32 -> U) forall U map_with_index, max max, max? max?, max_by(&block : T -> U) forall U max_by, max_by?(&block : T -> U) forall U max_by?, max_of(&block : T -> U) forall U max_of, max_of?(&block : T -> U) forall U max_of?, min min, min? min?, min_by(&block : T -> U) forall U min_by, min_by?(&block : T -> U) forall U min_by?, min_of(&block : T -> U) forall U min_of, min_of?(&block : T -> U) forall U min_of?, minmax minmax, minmax? minmax?, minmax_by(&block : T -> U) forall U minmax_by, minmax_by?(&block : T -> U) forall U minmax_by?, minmax_of(&block : T -> U) forall U minmax_of, minmax_of?(&block : T -> U) forall U minmax_of?, none?(&block)
none? none?, one?(&block) one?, partition(&block) partition, product(&block)
product(initial : Number, &block)
product
product(initial : Number) product, reduce(&block)
reduce(memo, &block) reduce, reject(&block : T -> ) reject, select(&block : T -> ) select, size size, skip(count : Int) skip, skip_while(&block) skip_while, sum(initial)
sum
sum(initial, &block)
sum(&block) sum, take_while(&block) take_while, to_a to_a, to_h to_h, to_set to_set

### Instance methods inherited from module `Iterable(T)`

chunk(reuse = false, &block : T -> U) forall U chunk, cycle(n)
cycle cycle, each each, each_cons(count : Int, reuse = false) each_cons, each_slice(count : Int, reuse = false) each_slice, each_with_index(offset = 0) each_with_index, each_with_object(obj) each_with_object

### Instance methods inherited from class `Reference`

==(other : self)
==(other) ==, dup dup, hash hash, inspect(io : IO) : Nil inspect, object_id : UInt64 object_id, pretty_print(pp) : Nil pretty_print, same?(other : Reference)
same?(other : Nil) same?, to_s(io : IO) : Nil to_s

### Class methods inherited from class `Reference`

new new

### Instance methods inherited from class `Object`

!=(other) !=, !~(other) !~, ==(other) ==, ===(other : JSON::Any)
===(other : YAML::Any)
===(other) ===, =~(other) =~, class class, dup dup, hash hash, inspect(io : IO)
inspect inspect, itself itself, not_nil! not_nil!, pretty_inspect(width = 79, newline = "\n", indent = 0) : String pretty_inspect, pretty_print(pp : PrettyPrint) : Nil pretty_print, tap(&block) tap, to_json(io : IO)
to_json to_json, to_pretty_json(indent : String = " ")
to_pretty_json(io : IO, indent : String = " ") to_pretty_json, to_s
to_s(io : IO) to_s, to_yaml(io : IO)
to_yaml to_yaml, try(&block) try

### Class methods inherited from class `Object`

from_json(string_or_io, root : String) : self
from_json(string_or_io) : self from_json, from_yaml(string_or_io) : self from_yaml

## Class Method Detail

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

Creates a new Array, allocating an internal buffer with the given capacity, and yielding that buffer. The 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

def self.each_product(arrays : Array(Array), reuse = false, &block) #
def self.each_product(*arrays : Array, reuse = false, &block) #
def self.from_json(string_or_io, &block) : 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.

def self.from_yaml(string_or_io, &block) #
def self.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']

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

def self.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

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

Creates a new empty Array.

def self.new(size : Int, &block : 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]]

def self.new(pull : JSON::PullParser, &block) #
def self.new(pull : YAML::PullParser, &block) #
def self.product(arrays) #
def self.product(*arrays : Array) #

## Instance Method Detail

def &(other : Array(U)) 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`.

def *(times : Int) #

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

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

def +(other : Array(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]

def -(other : Array(U)) 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]

def <<(value : T) #

Append. Alias for `#push`.

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

def <=>(other : Array) #

Combined comparison operator. Returns 0 if `self` equals other, 1 if `self` is greater than other and -1 if `self` is smaller 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

def ==(other : Array) #

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

def [](range : Range(Int, Int)) #

Returns all elements that are within the given range.

Negative indices count backward from the end of the array (-1 is the last element). Additionally, 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]   # raise IndexError
    a[5..10]   # => []
    a[-2...-1] # => ["d"]

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

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

Negative indices count backward from the end of the array (-1 is the last element). Additionally, 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]  # raise IndexError
    a[1, 2]  # => ["b", "c"]
    a[5, 1]  # => []

def []=(range : Range(Int, 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]

def []=(range : Range(Int, Int), 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]

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

Sets the given value at the given index.

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

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

    ary[3] = 5 # raises IndexError

def []=(index : 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]

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

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

If count is zero, value is inserted at index.

Negative values of index 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]

def clear #

Removes all elements from self.

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

def 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]]

def combinations(size : Int = self.size) #
def compact #

Returns a copy of `self` with all `nil` elements removed.

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

def compact! #

Removes all `nil` elements from `self`.

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

def concat(other : Enumerable) #

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

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

def concat(other : Array) #

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

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

def delete(obj) #

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"]

def delete_at(index : Int, count : Int) #

Removes count elements from `self` starting at index. 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 index 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

def delete_at(index : Int) #

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

def delete_at(range : Range(Int, Int)) #

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

def 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]]

def each_combination(size : Int = self.size, reuse = false) #
def each_combination(size : Int = self.size, reuse = false, &block) : Nil #
def each_permutation(size : Int = self.size, reuse = false) #

Returns an `Iterator` over each possible permutation of size of `self`.

    iter = [1, 2, 3].each_permutation
    iter.next # => [1, 2, 3]
    iter.next # => [1, 3, 2]
    iter.next # => [2, 1, 3]
    iter.next # => [2, 3, 1]
    iter.next # => [3, 1, 2]
    iter.next # => [3, 2, 1]
    iter.next # => #<Iterator::Stop>

By default, a new array is created and returned for each permutation. If reuse is given, the array can be reused: if reuse is an `Array`, this array will be reused; if reuse if truthy, the method will create a new array and reuse it. This can be used to prevent many memory allocations when each slice of interest is to be used in a read-only fashion.

def each_permutation(size : Int = self.size, reuse = false, &block) : Nil #

Yields each possible permutation of size of `self`.

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

By default, a new array is created and yielded for each permutation. If reuse is given, the array can be reused: if reuse is an `Array`, this array will be reused; if reuse if truthy, the method will create a new array and reuse it. This can be used to prevent many memory allocations when each slice of interest is to be used in a read-only fashion.

def each_repeated_combination(size : Int = self.size, reuse = false, &block) : Nil #
def each_repeated_combination(size : Int = self.size, reuse = false) #
def each_repeated_permutation(size : Int = self.size, reuse = false, &block) : Nil #
def fill(from : Int, count : Int, &block) #

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

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

    a = [1, 2, 3, 4, 5, 6]
    a.fill(2, 2) { |i| i * i } # => [1, 2, 4, 9, 5, 6]

def fill(from : Int, &block) #

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

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

    a = [1, 2, 3, 4]
    a.fill(2) { |i| i * i } # => [1, 2, 4, 9]

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

Yields each index of `self`, in the given range, to the given block and then assigns the block's value in that position. Returns `self`.

    a = [1, 2, 3, 4, 5, 6]
    a.fill(2..3) { |i| i * i } # => [1, 2, 4, 9, 5, 6]

def fill(&block) #

Yields each index of `self` to the given block and then assigns the block's value in that position. Returns `self`.

    a = [1, 2, 3, 4]
    a.fill { |i| i * i } # => [0, 1, 4, 9]

def fill(value : T, from : Int, count : Int) #

Replaces every element in `self`, starting at from and only count times, with the given value. Returns `self`.

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

    a = [1, 2, 3, 4, 5]
    a.fill(9, 2, 2) # => [1, 2, 9, 9, 5]

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

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

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

    a = [1, 2, 3, 4, 5]
    a.fill(9, 2) # => [1, 2, 9, 9, 9]

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

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]

def fill(value : T) #

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

    a = [1, 2, 3]
    a.fill(9) # => [9, 9, 9]

def first(n : Int) #

Returns the first n elements of the array.

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

def 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]

def insert(index : Int, object : T) #

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"]

def last(n : Int) #

Returns the last n elements of the array.

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

def map(&block : T -> U) forall U #

Optimized version of `Enumerable#map`.

def map!(&block) #

Invokes the given block for each element of `self`, replacing the element with the value returned by the block. Returns `self`.

    a = [1, 2, 3]
    a.map! { |x| x * x }
    a # => [1, 4, 9]

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

Optimized version of `Enumerable#map_with_index`.

def permutations(size : Int = self.size) #

Returns an `Array` with all possible permutations of size.

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

def pop(&block) #

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"

def 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"]

def pop(n : Int) #

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        # => []

def pop? #

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

def pretty_print(pp) : Nil #
def product(enumerable : Enumerable, &block) #
def product(ary : Array(U)) forall U #
def push(*values : T) #

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"]

def push(value : T) #

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]

def reject!(&block) #

Modifies `self`, deleting the elements in the collection for which the passed block returns `true`. Returns `nil` if no changes were made.

See also: `Array#reject`.

def repeated_combinations(size : Int = self.size) #
def repeated_permutations(size : Int = self.size) #
def replace(other : Array) #
def reverse #

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

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

def reverse! #

Reverses in-place all the elements of `self`.

def rotate(n = 1) #
def rotate!(n = 1) #
def sample(n : Int, random = Random::DEFAULT) #

Returns n number of random elements from `self`, using the given random number generator. Raises IndexError if `self` is empty.

    a = [1, 2, 3]
    a.sample(2)                # => [2, 1]
    a.sample(2, Random.new(1)) # => [1, 3]

def select!(&block) #

Modifies `self`, keeping only the elements in the collection for which the passed block returns `true`. Returns `nil` if no changes were made.

See also: `Array#select`.

def shift(n : Int) #

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          # => []

def shift #

Removes the first value of `self`, at index 0. This method returns the removed value. Raises `IndexError` if array is of 0 size.

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

def shift(&block) #
def shift? #
def shuffle(random = Random::DEFAULT) #

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

def shuffle!(random = Random::DEFAULT) #

Modifies `self` by randomizing the order of elements in the collection using the given random number generator. Returns `self`.

def size : Int32 #

Returns the number of elements in the array.

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

def sort #

Returns an array with all elements in the collection sorted.

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

Optionally, a block may be given that must implement a comparison, either with the comparison operator `#<=>` or a comparison between a and b, where a < b yields -1, a == b yields 0, and a > b yields 1.

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

Modifies `self` by sorting the elements in the collection.

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

Optionally, a block may be given that must implement a comparison, either with the comparison operator `#<=>` or a comparison between a and b, where a < b yields -1, a == b yields 0, and a > b yields 1.

def sort!(&block : T, T -> Int32) #
def sort_by(&block : T -> _) #
def sort_by!(&block : T -> _) #
def swap(index0, index1) #
def to_a #
def to_json(json : JSON::Builder) #
def to_s(io : IO) #
def to_unsafe : Pointer(T) #

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

def to_yaml(yaml : YAML::Builder) #
def 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]]

def uniq #

Returns a new `Array` by removing duplicate values in `self`.

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

def uniq(&block : T -> _) #

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

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

def uniq! #

Removes duplicate elements from `self`. Returns `self`.

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

def uniq!(&block) #

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

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

def unsafe_at(index : Int) #
def unshift(obj : T) #

Prepend. Adds obj 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"]

def unshift(*values : T) #

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

def update(index : Int, &block) #
def |(other : Array(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`.