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.
array[start..end]
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.
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 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 by rangea = array1[2..4] # from index 2 to 4b = array2[0..2] # from index 0 to 2c = array3[1..1] # from index 1 to 1d = array4[10..12] # out of rangee = array5[4..7] # from index 4 to 7puts "#{a}" # [3, 4, 5]puts "#{b}" # ["ab", "cd", "ef"]puts "#{c}" # ["Meta"]puts "#{d}" # nothing returned ; out of rangeputs "#{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.