Arrays and Hashes. What are they? How are they used?
Both arrays and hashes store information that we can retrieve or manipulate later, BUT they store information in very different ways.
Arrays store elements of one group. Below is an example of an array of cities in the great state of Minnesota.
Arrays are a list of something put together in a group. The items, or elements, in the array are stored in the order they are listed. Each position in the array is given an index number (starting from 0). To access an element you simply request that element by its position (index number).
array_of_cities_in_mn[0] will return ‘Watertown' array_of_cities_in_mn[1] will return ‘Minneapolis' array_of_cities_in_mn[2] will return ‘Buffalo'
Hashes also are a way to store information. The major distinction between arrays and hashes are that hashes are a group of elements, or keys, that are associated with another value.
Here is an example of a hash:
As you can see it is very important that we keep :graduated_from and “Watertown” linked together. This is an example of a key (:graduated_from) and value (“Watertown”). They are connected and need to stay connected. These pairs are not stored neatly in an index (specific order) like in an array. To access a value you simply search for its key.
my_life_in_minnesota[:graduated_from] will return “Watertown”.
*It is important to note that each key must be unique. I could not list two different cities that I live_in. That just wouldn’t make sense. However, the values can be repeated. I could potentially work_in and live_in the same city.
If you are deciding between arrays and hashes, just think—Do I have a list of elements or pairings of elements (key and value) that need to stick together?
If you have a list of elements–go with an array.
More examples of arrays:
Each of these examples are simply a list of items. If the order in which the elements where mixed up that would not change the information only how you would access the individual item as it would have a new index.
If you have pairings of elements –go with a hash.
More examples of a hashes:
Arrays and Hashes give you the ability to store information for later use. They are used in different way depending on the type of information you have (pairs or simply elements of one group).
Once you understand how to build basic arrays and hashes, go a little wild and create an array of hashes or hashes of arrays! What type of situations would you use them? How would retrieve information from them?
**Originally written for Dev Bootcamp Week 3 (Phase 0 Unit 1) May 12, 2015