...

/

Working with Arrays

Working with Arrays

Learn about arrays and how to operate on them in Ruby.

Defining arrays

While numbers, strings, true, false, and nil all represent simple, primitive things, Array objects (arrays) are more interesting and very useful.

Arrays are things that store other things. Think of an array as a list of things, or a special type of bag that we can throw things in. The bag itself is a thing (object) too.

Remember: An array is an object that stores other objects.

An array is created by separating values by commas and enclosing the list with square brackets, like so:

Press + to interact
[1, 2, 3]

This is a simple array that holds three numbers.

Note that elements in arrays always retain their order. Unlike elements in a real bag, which get shuffled around, an array always keeps its objects in the same defined order, unless we do something to change the order.

Arrays can contain all kinds of things:

Press + to interact
["A string", 1, true, :symbol, 2]

This creates an array with five elements. ...