12/1/2015
So now that we are learning to be ruby programmers we have to learn about arrays and hashes, To explain it in a simple non technical way. Arrays are like lists. When you make a christmas shopping list you have items like “toy”, “Shirt”, and “Book” on there. These could all be elements in your array. You can access them by looking at the list and looking at the second Item and you get “Shirt”. In ruby we would write something like list[1] to get that value. The reason we are using 1 as the index value is because ruby starts counting at zero. Hashes are like tables. So what if I wanted to specify that “Shirt” is for Dan? Then I could use a hash. Hashes are made up of key:value pairs. The key here is “Shirt” the value is Dan. What I am saying is the item I am buying, “Shirt”, is for the value “Dan”.
To get a bit more technical, arrays are used to house multiple scalar variables. What that means is basically an array is a list of variables that are accessible by using the array name and its index. The variables are stored at specific indexes in the array. You would use an array when making anything akin to a list. Beyond the scope of this post is the fact that you can have multidimensional and parallel arrays. A parallel array is two arrays side by side. Multidimensional arrays are like arrays within arrays, confusing right! Anyway you can store almost anything in an array even other arrays. So remember when you would use a list use an array!
About hashes; hashes are basically tables they are often called hash tables. In a hash you have a key and a value. Your keys should be unique, your values can repeat themselves. You would use a hash whenever you need to make a table. Hashes can use strings or symbols for their keys and almost any value for their values. You can access a value in a hash by typing the hashes name and the values key, so it would look like hash[“Shirt”] which would return “Dan”. Remember you would use hashes anytime you use tables.
I hope you guys learned a bit about hashes and arrays today! Thanks for checking out my blog! And checkout the code below to get started!
hash = Hash.new
hash = {
:toy => "Tom",
:Shirt => "Dan",
:Book => "Drew"
}
hash[:Shirt]
list = ["toy", "Shirt", "Book"]
list[1]