An Array is an ordered, integer-indexed collection of objects, called elements. Any object may be an Array element.
Array indexing starts at 0, as in C or Java.
A positive index is an offset from the first element:
Index 0 indicates the first element.
Index 1 indicates the second element.
…
A negative index is an offset, backwards, from the end of the array:
Index -1 indicates the last element.
Index -2 indicates the next-to-last element.
…
A non-negative index is in range if it is smaller than the size of the array. For a 3-element array:
Indexes 0 through 2 are in range.
Index 3 is out of range.
A negative index is in range if its absolute value is not larger than the size of the array. For a 3-element array:
Indexes -1 through -3 are in range.
Index -4 is out of range.
A new array can be created by using the literal constructor
[]. Arrays can contain different types of objects. For
example, the array below contains an Integer, a
String and a Float:
ary = [1, "two", 3.0] #=> [1, "two", 3.0]
An array can also be created by explicitly calling ::new with zero, one (the initial size of the Array) or two arguments (the initial size and a default object).
ary = Array.new #=> [] Array.new(3) #=> [nil, nil, nil] Array.new(3, true) #=> [true, true, true]
Note that the second argument populates the array with references to the same object. Therefore, it is only recommended in cases when you need to instantiate arrays with natively immutable objects such as Symbols, numbers, true or false.
To create an array with separate objects a block can be passed instead. This method is safe to use with mutable objects such as hashes, strings or other arrays:
Array.new(4) {Hash.new} #=> [{}, {}, {}, {}] Array.new(4) {|i| i.to_s } #=> ["0", "1", "2", "3"]
This is also a quick way to build up multi-dimensional arrays:
empty_table = Array.new(3) {Array.new(