Arrays
7 min · Ruby
Hold many values under one name, and reach for the one you want.
Enemy 1 of 5
Ordered collections with []
An array is a single variable that holds several values in a specific order, written inside square brackets and separated by commas, like ["apple", "banana", "cherry"]. Unlike a plain variable, which holds exactly one value, an array lets you group related values together and work with them as a unit.
Ruby indexes arrays starting at 0, the same convention used by most modern languages (Python, JavaScript, PHP, Dart included): the first element is at position 0, the second at position 1, and so on. You look up a value with square brackets after the array's name: fruits[0] gives you "apple", the very first element. This zero-based counting is one of the most common early stumbling points — the "first" item is at index 0, not 1.
You can also count backward from the end using negative indexes: fruits[-1] gives you the last element without needing to know exactly how many items are in the array — a handy Ruby-specific shortcut that many other languages don't offer directly.
Loading editor...