Creating Arrays

An array can be thought of as a list of values all placed under one heading (i.e., within one variable). Whereas a string might store a single thought, like something you need to purchase from the grocery store—kiwis, an array can be the entire shopping list: kiwis, cereal, milk, etc.

An array’s name abides by the same rules as any other variable: it may contain only letters, numbers, and underscores, and it cannot begin with a number or uppercase letter. Arrays can also be assigned values using the assignment operator. However, since arrays store multiple values, a slightly different syntax is used to assigning them:

numbers = [1, 2, 3]groceries = ['kiwis', 'cereal', 'milk']

The array’s elements, which is to say its values, ...

Get Ruby: Visual Quickstart Guide now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.