Arrays and Hashes are two data structures in the world of Ruby (and programming in general). The Array is a group of any type of object: strings, integers, even other arrays! An array is ordered and items can be called upon by their index number. The Hash is related to an array but the items that comprise a hash are a series of keys and values. A key is a name (usually a symbol) that is associated with a value that can be anything (string, integer, float, etc.). These pairs allow you to associate values with things other than just a series of sequential numbers. For example, if you had 5 mice and each had a number on its back (0-5), there would be no need to use a hash. An array would suffice because we could access the mice just based on the number on the back. But, if the mice were identified by say a random 5 digit number or an alphanumeric id, how would we store that info? The Hash allows the keys to be things other than numbers so we could store them there.
To define an array, I usually take the quick way and set the array name equal to a set of empty brackets:
array1 = []Then I can add elements to the array using the
array1 << thingmethod.
The hash can be defined similarly as above but should use curly braces instead of the standard bracket:
hash1 = {}To add key/value pairs to the hash at the time of creation the new style is shown below, keep in mind, all keys must be symbols for this style:
hash1 = { age: 27, name: "bob"}