Friday, December 30, 2011
Exercise 40: Dictionaries, Oh Lovely Dictionaries: Learn Ruby the Hard Way: Practicum
Ruby calls them "hashes", other languages call them, "dictionaries". Zed says he uses both names, but what they are called doesn't really matter. What does matter is what they do when compared to arrays.
An array lets you do this:
Arrays store their values in an ordered list, and you can reference and access those values by calling the index number from 0 to, well, whatever the last element in the array happens to be, and whatever that number is.
A hash works similarly, but you don't have to use numbers to access the elements stored in a hash. You can use anything. Here's an example:
[For the record, the example on the LRtHW site has a back slash for the multiplication sign. This doesn't work on my environments; both Ruby 1.8.7 and 1.9.2 give me an error. Removing the back slash works as expected. See below. I also let Zed and Rob know about this, so this may well be fixed by the time this entry appears... and has been :) ]
Instead of using numbers, we are using "symbols", which are effectively name tags, an they are easier to remember than trying to figure out where in an array something is.
Here's another way to do it.
So that's kinda cool, I can insert new items and give them a unique id and then if I print out the hash, I can see where it fits along with the number or id.
Hashes also let you delete stuff, too:
So here's the exercise for this go around, in case the previous wasn't enough to bring the point home :):
What You Should See
Go find the Ruby documentation for hashes and try to do even more things to them.
[There's a lot of stuff here! hash has a bunch of method options, most of which I'm just barely able to understand how I would use. For grins I played with merge, which allows the user to take two separate hashes and merge them together. Interestingly, if the second hash has a pair with a key that matches the first one, it's the second hash's value of the pair that will be used. See below.]
Find out what you can't do with hashes. A big one is that they do not have order, so try playing with that.
[ This is correct. They go in as you create them, and they get listed as they are ordered. the one difference is that, if you merge two hashes, then the location of the original hash key and value is replaced with the new value, but its ordering in the hash is preserved.]
This is cool, it's an item I can definitely see using for an application like a phone book or contact lookup. I'm sure it can be used for a lot more than that, and I look forward to more options I can use going forward. What I like about it is the fact that the key can be an actual word, which is a lot more logical way to consider doing a lookup compared to remembering or finding a number in an array.