March 2009
Intermediate to advanced
194 pages
4h
English
Another useful class is the Hash class. Hashes are a lot like arrays: they have a bunch of slots that can point to various objects. However, in an array, the slots are lined up in a row, and each one is numbered (starting from zero). In a hash, the slots aren’t in a row (they are just sort of jumbled together), and you can use any object to refer to a slot, not just a number. It’s good to use hashes when you have a bunch of things you want to keep track of but they don’t really fit into an ordered list. For example, we can make a dictionary for little C’s vocabulary:
dict_array = [] # array literal; same as Array.new |
dict_hash = {} # hash literal; same as Hash.new |
dict_array[0] = 'candle' |
dict_array[1] = 'glasses' |
dict_array[2] ... |