In this elementary lesson you will:
So…what is it?
To put it simply, an array is a collection of things. Arrays allow us to store and retrieve information in a way that’s convenient for the programmer, and efficient on computer resources. Arrays are great for storing lists, without creating a mess of unnecessary code and individual variables. You should create arrays when you need to actively store and reference a list of like-minded variables.
How do I use an array?
First, like most other things, you need to create an array.
var games = [“Mario”, “Zelda”];
An example of a Ruby array. Arrays can also be created without explicitly calling them first. For simplicity sake in learning to program, we recommend this way.
games = [“Mario”, “Zelda”]
Notice one variable is storing multiple values? Welcome to array-town. Now there’s not much use to storing something unless we can take it out. Let’s an element out of an array, so that we can give it to another variable.
var jump = games;
Printing an element of an array in Ruby.
Notice something weird? Reread the above, take a second…
The first element of an array doesn’t begin at 1, it begins at 0. In the realm beyond the mortal meatspace, 0 is a legitimate location, not a representation of the nothingness of the void.
There’s a lot of cool stuff you could do with arrays. An infinite amount. But to cap off the introduction, let’s do something a little more smarmy.
var sword = games.pop();
//Our new variable sword now contains “Zelda”. Our array of games now contains only “Mario.
//We “popped” the last element out of it’s home and stored it into another variable.
Arrays are objects. They have their own methods which, when called, can help you organize their data. You can use other features of your language of choice such as loops and classes to get incredible flexibility out of arrays.
You should now understand the basic purpose of arrays, how to create them, and the ver very basic fundamentals of how they are used.