Indexing Arrays in Ruby

In this tutorial, we will learn different ways in which we can index arrays in Ruby. Ruby is a zero index language meaning indices of builtin elements start with zero. Arrays are built in datastructures. So they start from 0 too.

Let us learn this using an example. Let us take a simple array with simple elements.

A = [1,2,3,4,5,6]

The array has six elements and indices from 0 to 5. The first element of the array(or any array for that matter) has an index of 0 and the last element of the array has the index of 5. So the general rule of thumb is the index for any array starts at 0 and ends at one less than the length of the array. You have to be aware of this fact if you are coming from a one index language like Octave. You can access the element at each index by calling Array[index]

Here are the elements of A accessed by the index.



Ruby also supports negative indices. Negative indices can be used to retrieve elements of an array starting from the last and ending at the first. Negative indices start at from -1 and go until the length of the array.(Notice the difference between postive indexing and negative indexing. Postive indices start from 0 and negative indices start from -1).

Here are the elements of A accessed by negative indices



If you want to know the index of a particular value in a array, you can learn it by using the Array.index(value) command.

In order to illustrate this, let me define an Array A = [2,3,4,5]. I want to know the index of value 4 in the array. So I type A.index(4) which will return me 2. You can read more about Array.index at