Arrays

Store a list of things in one variable

7 min read

Imagine you need to keep track of a whole list of items, like your three favorite fruits. You could create three separate variables, but Ruby gives you a much better tool for this job: the array.

What is an array?

An array is an ordered list of values, all stored inside a single variable. You create one using square brackets, with each item separated by a comma.

fruits = ["apple", "banana", "cherry"]
puts fruits

This prints all three fruits, one on each line. The array remembers the order you put the items in, and that order will not change unless you change it yourself.

Getting one item from an array

Every item in an array has a position number called an index. In Ruby, and in most programming languages, counting starts at zero, not one.

fruits = ["apple", "banana", "cherry"]
puts fruits[0]
puts fruits[1]

This prints "apple", then "banana". So fruits[0] means "the first item," even though it looks like zero.

Adding and changing items

Arrays are not fixed once you create them. You can add a new item to the end using <<, or replace an existing item by assigning to its index.

fruits = ["apple", "banana", "cherry"]
fruits << "mango"
fruits[1] = "blueberry"
puts fruits

After this code runs, the array contains "apple", "blueberry", "cherry", and "mango", in that exact order.

Finding the size of an array

You can ask an array how many items it holds using .length or .size, which both do the same thing. Running fruits.length on our original list of three fruits prints 3.

Arrays can hold any kind of value, including numbers, strings, or even other arrays. This flexibility makes them one of the most useful tools in Ruby.

Quick check

Q1 What position does fruits[0] refer to in an array?

Q2 Which method tells you how many items are in an array?

Want to save your progress? It's free.

Create a free account