Hash vs. Array Analogy: Am I Understanding The Hash Concept?
Hi all, So from what I gather, a hash is like a phone book, if you know something about the data you're trying to get to like the last name Johnson (the key) the phone book will "return" (or you turn to the page) the name E. J. (the data that it's storing that is connected to the key).
However, an array is like a pile of garbage: it's not organized except by number. We have no idea what the contents of the garbage pile is so we have to pick a random number in the pile and pull out the contents to see what garbage item #5 is.
So if I'm correct about the difference between an array and a hash, why the heck would anyone use an array over a hash? A hash seems much more human friendly.
Stephen Beckstrand11,129 Points
Hello again nekilof,
I think your analogy of a phone book for a hash is good, though I would think of it more like keys are the fields in a phone book, and the values are the actual values written in those fields.
For instance, If you have a phone book that has:
First Name: John
Last Name: Smith
Phone Number: 123-456-7890
Address: 123 Awesome Ln, Awesomeland AW, 12345
You could say that First Name, Last Name, Phone Number, Address are all the keys within a hash, and that John, Smith, 123-456-7890, 123 Awesome Ln, Awesomeland AW, 12345 are the values connected to those keys.
An Array is just a list, and sometimes we dont need values tied to keys, we just want a list of things. One of the examples used by Treehouse is a shopping list. with an array, we could do something like: Bread, Milk, Eggs. That would be easier in an array. Additionally, using our phone book analogy, what if John Smith had two numbers? Instead of having two different phone number keys, you could just use the existing phone number key, and assign it to an array with a list of two phone numbers.
You're right, a hash can be very human friendly as you could essentially set up fields, or subjects with content under each, whereas an array is just a list. However, a lot of the time, you will need the ability to just have a simple list.