Hashes (sometimes known as associative arrays or dictionaries) are
similar to arrays, in that they are indexed collectives of object
references.
However, while you index arrays with integers, you can
index a hash with objects of any type: strings, regular expressions,
and so on. When you store a value in a hash, you actually supply two
objects---the key and the value. You can subsequently retrieve the
value by indexing the hash with the same key. The values in a hash can
be any objects of any type. The example that follows uses hash literals: a
list of
key =>
value pairs between braces.
h = { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' }
|
|
h.length
|
� |
3
|
h['dog']
|
� |
"canine"
|
h['cow'] = 'bovine'
|
h[12] = 'dodecine'
|
h['cat'] = 99
|
h
|
� |
{"cow"=>"bovine", "cat"=>99, 12=>"dodecine", "donkey"=>"asinine", "dog"=>"canine"}
|
Compared with arrays, hashes have one significant advantage: they can
use any object as an index. However, they also have a significant
disadvantage: their elements are not ordered, so you cannot easily use
a hash as a stack or a queue.
You'll find that hashes are one of the most commonly used data
structures in Ruby. A full list of the methods implemented by class
Hash
starts on page 317.