Programs often have to manage collections of variables. For example, a program that manages your calendar must have a list of the days of the week. Each day must be stored in a variable, and a list of them can be stored together in an array variable. Through that one array variable, you can access each of the days.
Creating Empty Arrays
You can create an empty array by creating a new Array object and storing it in a variable. This array will be empty; you must fill it with other variables to use it. This is a common way to create variables if you were to read a list of things from the keyboard or from a file.
In the following example program, an empty array is created using the array command and the assignment operator. Three strings (ordered sequences of characters) are read from the keyboard and "pushed," or added to the end, of the array.
array = Array.new
str = gets.chomp
Use an Array Literal to Store Known Information
Another use of arrays is to store a list of things you already know when you write the program, such as the days of the week. To store the days of the week in an array, you could create an empty array and append them one by one to the array as in the previous example, but there is an easier way. You can use an array literal.
In programming, a "literal" is a type of variable that's built into the language itself and has special syntax to create it. For example, 3 is a numeric literal and "Ruby" is a string literal. An array literal is a list of variables enclosed in square brackets and separated by commas, like [ 1, 2, 3 ]. Note that any type of variables can be stored in an array, including variables of different types in the same array.
The following example program creates an array containing the days of the week and prints them out. An array literal is used, and the each loop is used to print them. Note that each is not built into the Ruby language, rather it's a function of the array variable.
days = [ "Monday",
Use the Index Operator to Access Individual Variables
Beyond simple looping over an array--examining each individual variable in order--you can also access individual variables from an array using the index operator. The index operator will take a number and retrieve a variable from the array whose position in the array matches that number. Index numbers start at zero, so the first variable in an array has an index of zero.
So, for example, to retrieve the first variable from an array you can use array, and to retrieve the second you can use array. In the following example, a list of names are stored in an array and are retrieved and printed using the index operator. The index operator can also be combined with the assignment operator to change the value of a variable in an array.
names = [ "Bob", "Jim",
"Joe", "Susan" ]
puts names # Bob
puts names # Joe
# Change Jim to Billy
names = "Billy"