Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialA X
12,842 PointsHash 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.
1 Answer
Stephen Beckstrand
11,169 PointsHello 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.
A X
12,842 PointsA X
12,842 PointsHi Stephen, can you elaborate on when in programming commonly one would just use an array vs a hash? Or are the times when an array is more useful than a hash just too numerous?