Hashes are so awesome that I am writing about them again! I first talked about what a hash is and how to access something that is already inside of your hash. What if you want to make your own hash from scratch!? Once you have made your hash you want to add more key, value pairs to your hash. Then you want to show everyone all the awesome information in your hash by printing it out! That’s so much stuff and I am going to break it all down for you…
I want to make my hash about all the different movies I like and for each movie I want to write why I liked it.
- Make the “movies” hash
- We created the hash called “movies”.
- Our key is “Hard Day’s Night”
- The value is “The Beatles”
A LITTLE REVIEW: What if I want to print out “The Beatles!”?
- I would write: movies[“Hard Day’s Night”]
Awesome! Now “Hard Day’s Night” isn’t the only movie I like so let’s add another movie to our “movies” hash.
- First we have the name of the hash “movies” followed by [] which contain the name of the movie we want to add “High Fidelity”. “High Fidelity” becomes our key and it is equal to “John Cusack and Jack Black” which will become the value.
- SO if we were to look at our hash again we would now see…
- Now we want to show everyone our “movies” hash. We want to print to the screen what the name of the movie is and why we like it.
- IF we were to write: puts movies it would print out our hash, but we want to make it look a little neater for people to read, so let’s write the following…
- Whoa..there is a lot going on here! Let’s break this all down…
- We see the name of hash “movies” followed by “.each”. What “.each” is saying is, “I want to do something to EACH item that is in this hash”.
- The next word we see is “do”. So for EACH item in the hash we want to “do” something.
- Then we see “|key, value|” and this is saying what we want to work with. *Note these words are just place holders and you can really call them anything you would like and I can go over this more in another post!
- On the next line we see our friend “puts”, this is going to “put” to the screen what is in the parenthesis.
- What is inside our parenthesis are #{key}: #{value}…what this means is that as we go through our hash we want to print out the key followed by an colon then print the value.
- That’s all we want to do for now, so we write “end”.
- Here is what you will see printed to the screen…
Have fun with hashes!




