- 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

# module Indexable(T)

## Overview

A container that allows accessing elements via a numeric index.

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

Types including this module are typically `Array`-like types.

## Included Modules

- Enumerable(T)
- Iterable(T)

## Direct including types

- Array(T)
- BitArray
- Deque(T)
- Slice(T)
- StaticArray(T, N)
- Tuple(*T)

## Defined in:

## Instance Method Summary

- #[](index : Int)

  Returns the element at the given index.

- #[]?(index : Int)

  Returns the element at the given index.

- #at(index : Int, &block)

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

- #at(index : Int)

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

- #bsearch(&block)

  By using binary search, returns the first element for which the passed block returns `true`.

- #bsearch_index(&block)

  By using binary search, returns the index of the first element for which the passed block returns `true`.

- #each(&block)

  Calls the given block once for each element in `self`, passing that element as a parameter.

- #each

  Returns an `Iterator` for the elements of `self`.

- #each_index(&block) : Nil

  Calls the given block once for each index in `self`, passing that index as a parameter.

- #each_index

  Returns an `Iterator` for each index in `self`.

- #empty?

  Returns `true` if `self` is empty, `false` otherwise.

- #equals?(other : Indexable, &block)

  Optimized version of `#equals?` used when `other` is also an `Indexable`.

- #equals?(other, &block)

  Determines if `self` equals other according to a comparison done by the given block.

- #first(&block)

  Returns the first element of `self` if it's not empty, or the given block's value.

- #first

  Returns the first element of `self` if it's not empty, or raises `IndexError`.

- #first?

  Returns the first element of `self` if it's not empty, or `nil`.

- #hash

  Returns a hash code based on `self`'s size and elements.

- #index(object, offset : Int = 0)

  Returns the index of the first appearance of value in `self` starting from the given offset, or `nil` if the value is not in `self`.

- #index(offset : Int = 0, &block)

  Returns the index of the first object in `self` for which the block returns `true`, starting from the given offset, or `nil` if no match is found.

- #last

  Returns the last element of `self` if it's not empty, or raises `IndexError`.

- #last(&block)

  Returns the last element of `self` if it's not empty, or the given block's value.

- #last?

  Returns the last element of `self` if it's not empty, or `nil`.

- #reverse_each(&block) : Nil

  Same as `#each`, but works in reverse.

- #reverse_each

  Returns an `Iterator` over the elements of `self` in reverse order.

- #rindex(offset = size - 1, &block)

  Returns the index of the first object in `self` for which the block returns `true`, starting from the last object, or `nil` if no match is found.

- #rindex(value, offset = size - 1)

  Returns the index of the last appearance of value in `self`, or `nil` if the value is not in `self`.

- #sample(random = Random::DEFAULT)

  Returns a random element from `self`, using the given random number generator.

- #size

  Returns the number of elements in this container.

- #unsafe_at(index : Int)

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

- #values_at(*indexes : Int)

  Returns a `Tuple` populated with the elements at the given indexes.

- #zip(other : Indexable, &block)
- #zip(other : Indexable(U)) forall U
- #zip?(other : Indexable, &block)
- #zip?(other : Indexable(U)) forall U

### 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 Method Detail

def [](index : Int) #

Returns the element at the given index.

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

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

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

def []?(index : Int) #

Returns the element at the given index.

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

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

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

def at(index : Int, &block) #

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

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

def at(index : Int) #

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

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

def bsearch(&block) #

By using binary search, returns the first element for which the passed block returns `true`.

If the block returns `false`, the finding element exists behind. If the block returns `true`, the finding element is itself or exists infront.

Binary search needs sorted array, so `self` has to be sorted.

Returns `nil` if the block didn't return `true` for any element.

    [2, 5, 7, 10].bsearch { |x| x >= 4 } # => 5
    [2, 5, 7, 10].bsearch { |x| x > 10 } # => nil

def bsearch_index(&block) #

By using binary search, returns the index of the first element for which the passed block returns `true`.

If the block returns `false`, the finding element exists behind. If the block returns `true`, the finding element is itself or exists infront.

Binary search needs sorted array, so `self` has to be sorted.

Returns `nil` if the block didn't return `true` for any element.

    [2, 5, 7, 10].bsearch_index { |x, i| x >= 4 } # => 1
    [2, 5, 7, 10].bsearch_index { |x, i| x > 10 } # => nil

def each(&block) #

Calls the given block once for each element in `self`, passing that element as a parameter.

    a = ["a", "b", "c"]
    a.each { |x| print x, " -- " }

produces:

    a -- b -- c --

def each #

Returns an `Iterator` for the elements of `self`.

    a = ["a", "b", "c"]
    iter = a.each
    iter.next # => "a"
    iter.next # => "b"

The returned iterator keeps a reference to `self`: if the array changes, the returned values of the iterator change as well.

def each_index(&block) : Nil #

Calls the given block once for each index in `self`, passing that index as a parameter.

    a = ["a", "b", "c"]
    a.each_index { |x| print x, " -- " }

produces:

    0 -- 1 -- 2 --

def each_index #

Returns an `Iterator` for each index in `self`.

    a = ["a", "b", "c"]
    iter = a.each_index
    iter.next # => 0
    iter.next # => 1

The returned iterator keeps a reference to `self`. If the array changes, the returned values of the iterator will change as well.

def empty? #

Returns `true` if `self` is empty, `false` otherwise.

    ([] of Int32).empty? # => true
    ([1]).empty?         # => false

def equals?(other : Indexable, &block) #

Optimized version of `#equals?` used when `other` is also an `Indexable`.

def equals?(other, &block) #

Determines if `self` equals other according to a comparison done by the given block.

If `self`'s size is the same as other's size, this method yields elements from `self` and other in tandem: if the block returns true for all of them, this method returns `true`. Otherwise it returns `false`.

    a = [1, 2, 3]
    b = ["a", "ab", "abc"]
    a.equals?(b) { |x, y| x == y.size } # => true
    a.equals?(b) { |x, y| x == y }      # => false

def first(&block) #

Returns the first element of `self` if it's not empty, or the given block's value.

    ([1, 2, 3]).first { 4 }   # => 1
    ([] of Int32).first { 4 } # => 4

def first #

Returns the first element of `self` if it's not empty, or raises `IndexError`.

    ([1, 2, 3]).first   # => 1
    ([] of Int32).first # raises IndexError

def first? #

Returns the first element of `self` if it's not empty, or `nil`.

    ([1, 2, 3]).first?   # => 1
    ([] of Int32).first? # => nil

def hash #

Returns a hash code based on `self`'s size and elements.

See also: `Object#hash`.

def index(object, offset : Int = 0) #

Returns the index of the first appearance of value in `self` starting from the given offset, or `nil` if the value is not in `self`.

    [1, 2, 3, 1, 2, 3].index(2, offset: 2) # => 4

def index(offset : Int = 0, &block) #

Returns the index of the first object in `self` for which the block returns `true`, starting from the given offset, or `nil` if no match is found.

    [1, 2, 3, 1, 2, 3].index(offset: 2) { |x| x < 2 } # => 3

def last #

Returns the last element of `self` if it's not empty, or raises `IndexError`.

    ([1, 2, 3]).last   # => 3
    ([] of Int32).last # raises IndexError

def last(&block) #

Returns the last element of `self` if it's not empty, or the given block's value.

    ([1, 2, 3]).last { 4 }   # => 3
    ([] of Int32).last { 4 } # => 4

def last? #

Returns the last element of `self` if it's not empty, or `nil`.

    ([1, 2, 3]).last?   # => 3
    ([] of Int32).last? # => nil

def reverse_each(&block) : Nil #

Same as `#each`, but works in reverse.

def reverse_each #

Returns an `Iterator` over the elements of `self` in reverse order.

def rindex(offset = size - 1, &block) #

Returns the index of the first object in `self` for which the block returns `true`, starting from the last object, or `nil` if no match is found.

If offset is given, the search starts from that index towards the first elements in `self`.

    [1, 2, 3, 2, 3].rindex { |x| x < 3 }            # => 3
    [1, 2, 3, 2, 3].rindex(offset: 2) { |x| x < 3 } # => 1

def rindex(value, offset = size - 1) #

Returns the index of the last appearance of value in `self`, or `nil` if the value is not in `self`.

If offset is given, it defines the position to end the search (elements beyond this point are ignored).

    [1, 2, 3, 2, 3].rindex(2)            # => 3
    [1, 2, 3, 2, 3].rindex(2, offset: 2) # => 1

def sample(random = Random::DEFAULT) #

Returns a random element from `self`, using the given random number generator. Raises `IndexError` if `self` is empty.

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

abstract def size #

Returns the number of elements in this container.

abstract def unsafe_at(index : Int) #

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

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

Clients never invoke this method directly. Instead, they access elements with `#` 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.

def values_at(*indexes : Int) #

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

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

def zip(other : Indexable, &block) #
def zip(other : Indexable(U)) forall U #
def zip?(other : Indexable, &block) #
def zip?(other : Indexable(U)) forall U #