JavaScript & Donuts

Arrays & Hashes / when and how to use them

January 24, 2016

Alyssa Page

Both arrays and hashes are data structures. They allow adding data, accessing data and removing data. Let's create both with some data about a dog.


        dog_array = [["name", "Charlie"], ["age", 7], ["breed", "corgi"]]
        dog_hash = {
        :name => "Charlie",
        :age => 7,
        :breed => "corgi"
        }
      

So now we have create an array of arrays and a hash both containing the same information about a dog. Data can be added while creating both data structures or after the empty structures are created.

To access the data in an array we either need to know the index of where it is stored or iterate over each value until we find what we are searching for. Hashes on the other hand use unique keys to store and retrieve values. These are called key value pairs. So in order to find the age of the dog in the array we either have to know that it is stored at index [1][1] or iterate through the array to find it. In a hash we simply call the key


        dog_hash[:age] 
      

and it accesses the value of 7.

Both hashes and arrays are used to store data but it is important to know when to use them. Hashes make retrieving data much easier and faster since knowing the location is not neccessary. On the other hand, if you are wanting to iterate over a list of data, using an array and its methods would be easier.