To reference elements of an array, you will need more than the index positions. We can reference more than one element in Ruby. We specify the starting index, where we want to start the reference, and the length of elements we want to return.
This ensures that the code returns a sub-array that starts at that index and continues for the specified length.
array[start, length]
start
: The starting index of elements we want to reference.length
: The sub-array length to be returned, starting from the start
index.The code returns a sub-array of the original array, with the specified length
starting at the start
index.
In the example below, we create different arrays and then access or reference the elements they contain with the start
and length
arguments.
# create different kinds of arraysarray1 = [1, 2, 3, 4, 5]array2 = ["ab", "cd", "ef", "gh", "ij"]array3 = ["Google", "Meta", "Apple", "Netflix", "Amazon"]array4 = ["AWS", "Google Cloud", "Azure", "IBM Cloud"]array5 = [true, false, nil, "nil", "true"]# reference elements of the arraysa = array1[2, 3] # start from index 2 and return 3 elementsb = array2[0, 2] # start from index 0 and return 2 elementsc = array3[1, 1] # start from index 1 and return 1 elementd = array4[4, 100] # start from index 4 and return 100 elementse = array5[0, 5] # start from index 0 and return 5 elememts# print returned arraysputs "#{a}"puts "#{b}"puts "#{c}"puts "#{d}"puts "#{e}"
In the example above, we create arrays with different elements. We reference the arrays with start
and length
.
In line 16, we print [3, 4, 5]
because we want to start the reference at index 2
index, and the return length is 3.
In line 17, we return ["ab", "cd"]
because our reference starts at index 0
and the length of the array to be returned is 2. This pattern repeats for lines 18 and 20.
However, in line 19, we return an empty array because the index
is out of range. So, there is no element to return for that range.