Understanding an Array and Hash

January 24, 2015

In Ruby, arrays and hashes are very similar. Both are used to store and retrieve data. What makes them different is how you program them, and how they store and retrieve the data. Arrays store the data in an index starting at 0, where hashes collect a pair of information.

The above picture has four examples of arrays. As you can see each array we give a name, array_1, array_2, array_3, and array_4. Many objects can be given a name in Ruby, what makes an array different is that we call it with brackets [ ]. Inside those brackets is our data. As you can see, arrays can store all sorts of data; we can store intergers, strings and even other arrays. Think of an array and its data as a numbered list that starts at 0. The list starts at 0 and goes up incrementally. For example if we were to do array_2(0) we would get "red". And if we call array_2(2) we get "green". Do you see how call 0 returns the first item in the list, and how 2 returns the third item?

Now lets talk about hashes.

The picture above is a hash. Like arrays we can give them a name. Hashes are different because they use a curly bracket { }. And just like arrays inside those brackets are our data. Like I said before, hashes collect a pair of information. The first part of information is called the key, and the second part of the pair is the value. There can only be one of any particular key, but they can be as many similar values. For example, in the hash above we can only have one key of "Name", but we can change all the values to be equaled to "Bob" ("Name" => "Bob", "Age" => "Bob", "Eye Color" => "Bob"). When trying to retrieve a value, you will enter in the key. Again like the picture above, if we did hash_1("Name") it would return "Bob"

You can use both arrays and hashes to collect and store you data. Both are very useful and you will pick one over the other depending on what you would like to do with you data.