Introduction to arrays

Learn about arrays and how they are used in Ruby.

Introduction

An array is a set of data. For example, an array may consist of a list of tenants living in an apartment building, numbers where each number has some meaning like employee salary , or objects such that each object represents an employee with multiple properties like salary, age, name, and so on.

In Ruby, each element in the array can be of a different type. In other words, arrays look like a bucket where we can put apples, pears, tape recordings, and even a couple of model aircraft ships. But usually, arrays are homogeneous, meaning that all items, or elements, in an array are of the same type.

Using arrays

But the question is, why do we need arrays? Why would we need to put something into an array? The answer to these questions is quite simple. Arrays are useful because they represent a set of some data, and we can perform bulk operations on this data. Let’s say we have a list of visited cities:

arr = ['San Francisco', 'Moscow', 'London', 'New York']

We initialized the array with four elements inside of the type string. Ruby knows it’s an array because we used square brackets for array definition. We can perform a variety of different valuable operations on this data. For example, we can get the number of elements, representing the number of visited cities:

Get hands-on with 1200+ tech skills courses.