The Hash Class

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] = ​'truck'
dict_array[3] = ​'Alicia'
dict_hash[​'shia-a'​] = ​'candle'
dict_hash[​'shaya'​ ] = ​'glasses'
dict_hash[​'shasha'​] = ​'truck'
dict_hash[​'sh-sha'​] = ​'Alicia'
dict_array.each ​do​ |word|
puts word
end
dict_hash.each ​do​ |c_word, word|
puts ​"​#{c_word}​: ​#{word}​"
end
candle
glasses
truck
Alicia
shia-a: candle
shaya: glasses
shasha: truck
sh-sha: Alicia

If I use an array, I have to remember that slot 0 is for “shia-a,” slot 1 is for “shaya,” and so on. But if I use a hash, it’s easy! Slot 'shia-a' holds the word for “shia-a,” of course. There’s nothing to remember. You might have noticed that when we used each, the objects in the hash came out in the same order we put them in. Older versions of Ruby (1.8 and earlier) did not work this way, so if you have an older version installed, be aware of this (or better yet, just upgrade).

Though people usually use strings to name the slots in a hash, you could use any kind of object, even arrays and other hashes. (I have no idea why you’d want to do this, though.)

weird_hash = Hash.new
weird_hash[12] = ​'monkeys'
weird_hash[[]] = ​'emptiness'
weird_hash[Time.new] = ​'no time like the present'

Hashes and arrays are good for different things; it’s up to you to decide which one is best for a particular problem. I probably use hashes at least as often as arrays; they’re wonderful.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.213.87