Ruby Hashes, initmidating?

Posted by morningrunning on July 11, 2017

I have recently re-discovered my frustration with hashes in Ruby. I played with hashes in the past but I didn’t go indepth with them until enrolling in the full stack developer program with Flatiron School. Hashes can be intimidating and frustrating. Of all the topics so far, Hashes has taken the longest for me to grasp, the thing that helped me with hashes was to compare them to arrays: both arrays and hashes are containers for data, the big difference is that in hashes, the data you store can be more in depth.

In hashes you have two parts, the Key and the Value. Keys will either be a string or symbol and the Values can be anything you want. Another major difference between arrays and hashes is that there’s no order to a hash. Here’s the basic syntax for a hash:

my_hash = {"name" => "Ron"}

Inside of the squiggly braces you have two pieces of data, “name” is the Key and “Ron” is the Value. The “=>” symbols in the middle of the key and value is called a Hash Rocket. It’s a great name, I know!

So when might you need to use a hash? This is usually the main question I ponder each time I learn something new in Ruby, why would you use that and when?!

Say you have some data:

car_name = "Ford"

car_color = "blue"

top_speed = 150

you could store that in a hash!

car = { "name" => "Ford", "color" => "blue", "speed" => 150}

In my opinion, hashes get pretty complex, pretty quickly. It’s the most difficult and frustrating topic I’ve dealt with so far. I’m hoping that as time goes on, I’ll feel more and more comfortable with hashes. My primary goal is to practice some examples each day until it becomes almost like second nature. Speaking of which, back to practicing!