How to reference items in an array by range in Ruby

Array elements can be referenced by index, start index, length of the array to be returned, or by range. In this shot, we will learn reference elements in an array by the range method.

Here, the range specifies the position where the element should start from and the position where the element should end from. Therefore, the returned array will be the array of elements included in the range.

Syntax

array[start..end]

Parameter

The range or start..end is the range of elements to be returned. The range contains the start and the end, which is indicative of the index to start from and the index to end from.

Code example

In the example below, we will reference the elements of an array using the range method. To do this, we will create several arrays, and the values will be returned in arrays that contain the elements in the specified range.

# create different kinds of arrays
array1 = [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 by range
a = array1[2..4] # from index 2 to 4
b = array2[0..2] # from index 0 to 2
c = array3[1..1] # from index 1 to 1
d = array4[10..12] # out of range
e = array5[4..7] # from index 4 to 7
puts "#{a}" # [3, 4, 5]
puts "#{b}" # ["ab", "cd", "ef"]
puts "#{c}" # ["Meta"]
puts "#{d}" # nothing returned ; out of range
puts "#{e}" # ["true"]

In the code above, line 18 prints nothing because the specified start index is out of range.

Since the range starts from the fourth element, which is "true", and no other element exists out of that range, "true" is returned.

Free Resources