When we create arrays in Ruby, it is obvious that its items or elements will be referenced at a certain point in our program. In this shot, we will learn how to reference the elements of an array using index reference.
Read up on How to reference elements of an array by index and length in Ruby.
This is the simplest method or way of referencing the elements of an array. It is also an easier method. Here, the index refers to the position of the element
Note: The first element of an array always has 0 as its index.
array[index]
Index: This is the index position of the element that we want to reference or access.
The value returned is the element at the index
. The index here is an integer value.
Note: Negative index or indices count backwards. That is, they count from the end of the array.
In the code below, we will create arrays and reference their elements by using positive integers as our index values.
See the example below:
# create arraysarray1 = [1, 2, 3, 4, 5]array2 = ["a", "b", "c", "d", "e"]array3 = ["Google", "Meta", "Netflix", "Apple", "Amazon"]# reference elementsputs array1[4] # index 4 element = 5puts array2[0] # index 0 element = "a"puts array3[1] # index 1 element = "Meta"
In the code above, we created array elements and referenced some of their elements using positive indices. In the next example, we will use negative indices.
As was noted earlier, when we pass a negative index, the element count then begins backwards. Therefore, counting will begin from the end of the array.
See the code below:
# create arraysarray1 = [1, 2, 3, 4, 5]array2 = ["a", "b", "c", "d", "e"]array3 = ["Google", "Meta", "Netflix", "Apple", "Amazon"]# reference elementsputs array1[-1] # last index = 5puts array2[-5] # fifth index from the end = "a"puts array3[-4] # fourth index from the end = "Meta"
In the code above, when we pass a negative index, the counting begins from the end of the array.
Note: When we pass an integer that is out of range, nothing is returned.
See the example given below:
# create arraysarray1 = [1, 2, 3, 4, 5]array2 = ["a", "b", "c", "d", "e"]array3 = ["Google", "Meta", "Netflix", "Apple", "Amazon"]# pass integer that is out of rangeputs array1[10] # prints nothingputs array2[7] # prints nothingputs array3[8] # prints nothing
We can also reference elements using the index as well as the length of the array in Ruby.