class Array(T)
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)
See Array
literals in the language reference.
An Array
can have mixed types, meaning T will be a union of types, but these are determined
when the array is created, either by specifying T or by using an array literal. In the latter
case, T will be set to the union of the array literal elements' types.
When creating an empty array you must always specify T:
[] of Int32 # same as Array(Int32)
[] # syntax error
An Array
is implemented using an internal buffer of some capacity
and is reallocated when elements are pushed to it when more capacity
is needed. This is normally known as a dynamic array.
You can use a special array literal syntax with other types too, as long as they define an argless
.new
method and a <<
method. Set
is one such type:
set = Set{1, 2, 3} # => Set{1, 2, 3}
set.class # => Set(Int32)
The above is the same as this:
set = Set(typeof(1, 2, 3)).new
set << 1
set << 2
set << 3
Included Modules
- Comparable(Array(T))
- Indexable::Mutable(T)
Defined in:
nason/any.crnason/to_json.cr
Constructors
Class Method Summary
-
.from_nason(string_or_io, &) : Nil
Parses a
String
orIO
denoting a NASON array, yielding each of its elements to the given block.
Instance Method Summary
Instance methods inherited from class Reference
==(other : NASON::Any)
==
Instance methods inherited from class Object
===(other : NASON::Any)
===,
nil_or_null?
nil_or_null?,
not_null!
not_null!,
null?
null?,
to_nason(io : IO) : Nilto_nason : String to_nason, to_pretty_json(indent : String = " ") : String
to_pretty_json(io : IO, indent : String = " ") : Nil to_pretty_json
Class methods inherited from class Object
from_nason(string_or_io, root : String)from_nason(string_or_io) from_nason
Constructor Detail
Class Method Detail
Parses a String
or IO
denoting a NASON 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 "nason"
Array(Int32).from_nason("[1, 2, 3]") do |element|
puts element
end
Output:
1
2
3
To parse and get an Array
, use the block-less overload.