Arrays
7 min · Ruby
Hold many values under one name, and reach for the one you want.
Enemy 1 of 5
Ordered collections with []
This code makes an array of three fruits and prints the first one, using index 0 because counting starts at 0. Press Run to see it.
Why this works
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.
Rena
Your AI tutor. She walks you through each step.
Asking for help is part of coding. Rena reads your code and gives you a hint. She is free with an account: 20 hints a day.