Computer Science Canada Hashes |
Author: | wtd [ Thu Mar 31, 2005 1:25 pm ] | ||||||||||||
Post subject: | Hashes | ||||||||||||
A Hash, or "associative array" can be thought of as very similar to a regular array, except that instead of indexing by numbers we can (in terms of Ruby at least) index by anything. Most commonly we use strings. So, if I want to have information about an individual, I could write:
Now, how to I retrieve the name? Oh, right. I need to remember that it's the first element in the array.
Now I could change the age:
But, in these cases I have to go back and look at the original creation of the array to see where each item is. There has to be a better way. There is. Instead of using an array, use a hash.
Now, let's get the name again.
And let's change the age.
Any other questions? ![]() |
Author: | Tony [ Thu Mar 31, 2005 3:06 pm ] |
Post subject: | |
I was actually hoping for a bit more advanced hash handling. Such as looping through the elements and adding new hashes to the list. |
Author: | wtd [ Thu Mar 31, 2005 3:57 pm ] | ||||||||||
Post subject: | |||||||||||
Getting all keys:
Getting all values:
Looping:
Determining if a hash contains a particular key or value:
Adding to a hash:
|
Author: | wtd [ Thu Mar 31, 2005 11:25 pm ] | ||||||||
Post subject: | |||||||||
More. Let's start with removing entries from a hash if they meet certain conditions. Ket's say we want to remove any entry where the value is exactly two times the key.
new_hash is now:
Next... ever want the keys and values switched?
And one last trick: Ever want to retrieve multiple entries into an array?
|
Author: | wtd [ Fri Apr 01, 2005 11:59 pm ] |
Post subject: | |
Anything else anyone would like to know about Ruby hashes? |
Author: | Tony [ Sat Apr 02, 2005 1:06 pm ] |
Post subject: | |
thx wtd, awesome examples as always ![]() |