Accessing Arrays
Explore how to access specific elements in Ruby arrays using indexes and how to modify array contents. Understand different ways to define arrays including shortcut syntaxes like %w for strings and %i for symbols, enabling you to write concise and readable Ruby code.
We'll cover the following...
Using indexes
So far, we have been iterating over an array. Now, let’s look at how we can access a particular element of an array. We can access the array by using an index. Indexes can be tricky but, at the same time, they’re easy to use. An index can be described as the number of elements minus one. In other words, if we want to access the fifth element of the array, we’ll need an index with a value of 4. Let’s create an array with five strings in REPL:
The size of the array is 5. We have five elements inside this array. Let’s get to the fifth element. To access the fifth element, we will need an index with a value of 4: