Hashes vs Arrays in Ruby

Nick Silas
2 min readDec 9, 2021

So I have been revisiting work I had done during my program. I thought today would be a good day to go over some basics for those who are just getting into programming.

One of the first things you will learn when you just get into coding is the use of an array. It makes sense, it is pretty much just a box to group things together. They are organized (unless changed) based off the order they enter the array. The first item starts at 0 and the second is 1. Arrays can be helpful but if you worked at a law office, you wouldn’t put all the paperwork you have into boxes and expect to find stuff easily. Hashes are another type of box but I think of them more like a filing cabinet. They have what is called a key value pair. What does this mean? The key in a key value pair is what you would label the value as. An example, if I was setting up a filing system for a law office, I would want to have a way to find all paperwork for a person by their name. The key in the hash would be name and the value would be whatever the persons name is. If I have multiple clients in my filing cabinet, I would be able to sort the hash where the key of name is equal to the value of Jeremy Renner. Arrays would make that much harder because items are organized in a way where matching the key to a value is what arrays are good for. I may use an array when I sort my hashes. If i wanted to find out who has yet to pay their bill to my law office, I could sort my hash based off of a value > 0 with a key of balance due. From there, I could put that into an array where I may only want to put the name of anyone who has a positive balance.

The more you start playing around with arrays and hashes, you will see that hashes are more organized and easier to store objects better than an array. I hope this helps anyone who might be lost when it comes to this difference.

--

--