Cora Hays-Magan

An enthusiastic coder

Arrays and Hashes

Save, Store, and Get the Data

August 15, 2015

Arrays and hashes hold things in Ruby. Think of a grocery list, the list in an array looks like this:

grocery_list = ["apples", "bananas", "wine vinegar", "eggs", "baking soda", "carrots", "flour", "potatoes, "baking powder", "beef chuck"]

Nice! That's a list. Now I know what to buy.

So a list of items is an array. It's a container to hold items in a group and can be referenced by the index number, starting with `0`. Why zero? The first item in an array is at the 0 point and the count goes up from there. If the last item is desired, you don't need to know how many items are in the array, just reference `-1`. In an array, order matters.

But, what if you don't want to walk with all of those heavy items home? How would you narrow down the list at the store? You could do by weight or price, but some of those items are for a yummy meal and others are random items. Which is important? In an array, the list has no organization of meaning other than the order position, index, of each item. I don't know what I must carry home versus what I should carry home.

A hash is similar to an array but with key/value pairs. Like arrays, hashes are also known as associative arrays. While an array's order is its index, a hash allows you to look up an object with any object type. Huh?

Take the same list and put it in a hash:

grocery_list = grocery_list = { :apple_pie => "apples", :pancakes => ["bananas", "baking powder", "flour"], :beef_and_carrot_meal => ["wine vinegar", "eggs", "carrots", "beef chuck"], :restock => "baking soda", :side_dish => "potatoes" }

Now, looking at the list, I know that if I don't get the apples, I can't make apple pie and if I decided to not spend the cash on the beef, I won't have the beef and carrots meal. This helps my decision making. Hashes help and pie is important.

Hashes are reference through a few methods, and the order doesn't matter:


Or by using the `fetch` method


You may have noticed the use of `:` before the name of the key when pulling out the value paired with it. Use of a `:` before a value in ruby denotes a symbol. More on that later. Just know that you could also use a string as the key to a value in your hash. If apple pie was listed in the hash instead as "apple pie", you'd look up it's ingredients with:

grocery_list["apple pie"].

With a hash, I know the beef and carrots don't need to be lugged home, but the apples are quite necessary.

The return for method_each is [1,2,3] but method_map! changes list to [3,6,9]. So map can destruct the object and each can't, but kittens are always cute.