Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to reference elements of an array by index and length in Ruby

okwudili onyejiaku

To reference elements of an array, you will need more than the index positions. We can reference more than one element in Ruby. We specify the starting index, where we want to start the reference, and the length of elements we want to return.

This ensures that the code returns a sub-array that starts at that index and continues for the specified length.


array[start, length]


  • start: The starting index of elements we want to reference.
  • length: The sub-array length to be returned, starting from the start index.

Return value

The code returns a sub-array of the original array, with the specified length starting at the start index.


In the example below, we create different arrays and then access or reference the elements they contain with the start and length arguments.

# 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 of the arrays
a = array1[2, 3]    # start from index 2 and return 3 elements
b = array2[0, 2]    # start from index 0 and return 2 elements
c = array3[1, 1]    # start from index 1 and return 1 element
d = array4[4, 100]  # start from index 4 and return 100 elements
e = array5[0, 5]    # start from index 0 and return 5 elememts

# print returned arrays
puts "#{a}"
puts "#{b}"
puts "#{c}"
puts "#{d}"
puts "#{e}"

In the example above, we create arrays with different elements. We reference the arrays with start and length.

In line 16, we print [3, 4, 5] because we want to start the reference at index 2 index, and the return length is 3.

In line 17, we return ["ab", "cd"] because our reference starts at index 0 and the length of the array to be returned is 2. This pattern repeats for lines 18 and 20.

However, in line 19, we return an empty array because the index is out of range. So, there is no element to return for that range.



View all Courses

Keep Exploring