How can we reference the elements of an array in Ruby by index?

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.

Reference by index

array[index]

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.

Syntax

array[index]

Parameter

Index: This is the index position of the element that we want to reference or access.

Return value

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.

Code example: Positive indices

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 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 will use negative indices.

Code example: 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 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 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 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.

Free Resources