Index operator is used for constant time look-up

Generally, the index operator ([]) refers to a way of accessing an element from a sequential data in constant time. This fast random access is possible because data are managed in a contiguous memory layout.

Strings for example, the index operator can be used to access specific characters. Then you can simply retrieve the value or even modify the original data (Ruby strings are mutable objects).

str = "hello"
str[0] # => "H"

str[0] = 'H'
str # => "Hello"

Another example would be an array. When an array is declared, it allocates a block of contiguous memory allowing you to access, retrieve, and/or modify data in constant time.

int arr = {1,1,2,3,4}; // block of memory allocated for 5 ints
arr[0] = 0;
arr // => [0, 1, 2, 3, 4]

If data are not stored contiguously in memory, index-based constant-time access using the index operator is not possible ([[Hash tables use key-based lookup]]). When data are laid out adjacent to each other, the system can locate any element by calculating an offset from the first element (Variable name is a pointer to the first element).

Backlinks: