Access
One can access individual items in an array by appending to the array another
set of square brackets enclosing the desired index. []
is a method that can
use a special syntax. Try accessing array elements for yourself!
got_characters = ["Robb", "Sansa", "Arya", "Bran", "Rickon"]
got_characters[0] # => "Robb" # got_characters.[](0) is equivalent but uglier
got_characters[3] # => "Bran"
got_characters[20] # => nil (nothing exists at this index)
Try running the code. (Click the run button.)
Arrays are zero-indexed, i.e., the first element of the array is at the zeroth
index. In the above example, the string "Robb"
is the first element and
therefore, the zeroth index. The second element of the array is at the first
index. "Sansa"
, the second element, is at the first index.
One can also access array elements using negative indices. The last element of the array is at the -1 index, the penultimate is at -2, etc. With negative indices, you essentially start at the end of the array and work your way backward.
got_characters = ["Robb", "Sansa", "Arya", "Bran", "Rickon"]
last = got_characters[-1] #=> "Rickon"
third_to_last = got_characters[-3] #=> "Arya"
last + " " + third_to_last #=> "Rickon Arya"
Try running the code. (Click the run button.)
One can access multiple elements in an array by using ranges instead of single indices. Doing so returns another array.
got_characters = ["Robb", "Sansa", "Arya", "Bran", "Rickon"]
got_characters[0..2] #=> ["Robb", "Sansa", "Arya"]
got_characters[0...-1] #=> ["Robb", "Sansa", "Arya", "Bran"]
Try running the code. (Click the run button.)
0..2
is a range object, another data structure. The two dots indicate that the
range is inclusive, i.e., the range comprises all integers from 0
to 2
,
including 2
. Three dots indicate an exclusive range: 0...11
is equivalent to
0..10
. One can also declare a range of characters (e.g., "a".."c"
,
"A"..."D"
). One can type convert a range to an array using the to_a
method:
(0..3).to_a #=> [0,1,2,3]
("A"..."D").to_a #=> ["A", "B", "C"]
Try running the code. (Click the run button.)
Although the range 0...-1
in got_characters[0...-1]
is technically empty,
when using a range in array access, -1 is equivalent to the array's length minus
one.
got_characters = ["Robb", "Sansa", "Arya", "Bran", "Rickon"]
got_characters[0...-1] == got_characters[0...(got_characters.length - 1)] #=> true
Try running the code. (Click the run button.)
Ruby provides idiomatic methods for accessing the first and last elements of arrays:
got_characters = ["Robb", "Sansa", "Arya", "Bran", "Rickon"]
got_characters.first #=> "Robb"
got_characters.last #=> "Rickon"