When we create arrays in Ruby, it is very obvious that its items or elements will surely be referenced at a certain point in our program. In this shot, we shall look at how to reference elements of an array using index reference.
Click here to read on how to reference elements of an array by index and length in Ruby
This is of course the simplest method or way of referencing elements of an array. It is easier to do. Here, the index means the element position.
We should know that the first element of an array has 0 as its index.
array[index]
index: This is the index position of the element we want to reference or access.
The value returned is the element at index
. The index here is an integer value.
NOTE: Negative index or indices count backward. That is, it counts from the end of the array.
In the code below, we will create arrays and reference their elements using positive integers as our index values.
See the example below:
# create arrays array1 = [1, 2, 3, 4, 5] array2 = ["a", "b", "c", "d", "e"] array3 = ["Google", "Meta", "Netflix", "Apple", "Amazon"] # reference elements puts array1[4] # index 4 element = 5 puts 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 shall use negative indices.
As noted earlier, when you pass a negative index, the element count then begins backwards. So counting will begin from the end of the array. See the following code below:
# create arrays array1 = [1, 2, 3, 4, 5] array2 = ["a", "b", "c", "d", "e"] array3 = ["Google", "Meta", "Netflix", "Apple", "Amazon"] # reference elements puts array1[-1] # last index = 5 puts array2[-5] # fifth index from the end = "a" puts array3[-4] # fourth index from the end = "Meta"
In the code below, when we pass negative index, counting then begins from the end of the array.
NOTE: When you pass an integer that is out of range, nothing is returned.
See example below:
# create arrays array1 = [1, 2, 3, 4, 5] array2 = ["a", "b", "c", "d", "e"] array3 = ["Google", "Meta", "Netflix", "Apple", "Amazon"] # pass integer that is out of range puts array1[10] # prints nothing puts array2[7] # prints nothing puts array3[8] # prints nothing
We can also reference elements using the index as well as the length of the array in Ruby.
RELATED TAGS
CONTRIBUTOR
View all Courses