Let’s start this post creating an array in Ruby (notice we are using the irb environment for our examples):
=> ["a", "b", "c", "d"]
You just put a list of items separated by commas between square brackets, assign it to a variable, and the array is created. In Ruby, the array indexes start at 0, so if you want to retrieve the first item from the array you just created, simply type:
Let's try to access an index out of range in the array.
You will get the nil object as return value.
You can retrieve several items at once using
array[i,n] in which
i is the starting index for the items you want, and
n is the number of items you want.
=> ["c", "d"]
You can make assignments to your array, replacing multiple items at once. Let's start modifying the array we created above.
=> ["B", "C"]
=> ["a", "B", "C", "d"]
It's possible to replace multiple items by a different number of items.
=> ["X", "Y", "Z"]
=> ["a", "X", "Y", "Z", "d"]
It's also possible delete them using the same technique.
=> ["a", "X"]
You can even insert new elements between the other elements of the array using
n=0. Let's create another array with symbols and insert one element between the others.
=> [:a, :b, :d, :e]
=> [:a, :b, :c, :d, :e]
You can think that the
array[i,n] syntax means: retrieve
n elements from the
array starting by the i-th position. If you try to access elements from the array using
n=0, you will get
 as a result (within the range of the array).
Actually, what is happening on the situation above, is that
n=0 will define a place between elements of the array, just between the indexes
For retrieving elements, you may see no reason to use
n=0. But, for inserting elements, it can be really useful. As you saw in the examples above, instead of replacing elements, you can insert new elements on the array using
n=0. So, to insert a new element at the end of an array we can do the following:
=> [:x, :y]
=> [:x, :y, :z]
Now, one interesting point to finish this article, observe the behaviours showed bellow:
In the example above the index 3 is out of range, since the array
b has three elements.
In the example showed above, we are on the tail of the array, so we're not out of range yet.
Now we are out of the range, so we received a nil object as return value.