An array is basically a list of elements stored in a container. Each element in the container acts like a variable, and you can inspect and change elements either individually or in groups. A hash is also a list of elements, but it differs from an array because each element in a hash must have what is called a key/value pair - i.e., each element, or key, has a value associated with it. The value can be a number, or a word or phrase (i.e., a string). Below is the basic syntax for creating an array in Ruby:
my_array = ["toys", "lamp", 2, "99 problems", "stacks on stacks on stacks"]
And here is the basic syntax for creating a hash in Ruby:
my_hash = { "sample_key" => "sample_value",
"address" => "1234 anytown USA",
"favorite candy" => "jelly-beans",
"number of cats" => 2
}
At this point, I’m not confident that I fully understand when one would use an array versus a hash, but I can think of at least a few examples of when each would be appropriate: a hash seems like a useful concept for storing names and passwords; also, if a company wanted to create a profile for its users, it might use a hash for storing the data (think about an online registration form, with fields such as name, email, address, some basic yes/no preference choices, etc.). All this data could be stored as key/value pairs in a hash that is devoted to a specific user. An array, on the other hand, seems more suited to gathering and storing information when you know you want more than just a series of key/value pairs - i.e., when the expected response is more open-ended. I might hazard a guess that the app on my phone that lets me craft my grocery list is storing my input in an array. In the picture on their itunes site, you can see the list on the right screen - it allows you to search their database of products, and add what you want to your own list. I'm guessing when I select and store items from their database in my list, the app uses an array to accomplish that process. It's a super-handy app!
In sum, at this point it seems to me that a significant difference between a hash and an array is scope- the hash has limitless key/value pairs; but everything is designed around the idea of that pair. The array is simply a limitless list, but each element in the list is treated equally. I’m confident there is much more to learn about the differences between arrays and hashes, and why you’d choose one over the other, and I look forward to expanding on this post as my familiarity and experience with these powerful tools expands!