Hashes also called Associative arrays, are similar to arrays in the way
that arrays use integers as their keys (array indexes). A hash allows
you to use any objects as keys.
Declaring a blank hash is as simple as writing -
A Hash can also be created using the method Hash#new-
A hash key-value pair can have any object as its key. e.g. price and
volume below, use objects of class String and Symbol respectively and
both are valid hashes-
In fact, a hash can have different object types as its keys. e.g.
a_hash below is a valid hash too-
In case you want to access a key that has not been added to a hash, a
default value is returned. If default is not set, nil
is returned. You can set the default value by passing it as an argument
to new or calling the Hash#default method -
Fetching values from a Hash and modifying it- you can fetch values from
a Hash by putting the key name in square bracket after the Hash name.
And just in case you want to modify them, writing the new value in
front of the above is enough.
If you want to list down all the keys in a Hash,
price.keys will get you an array of all the keys in hash
You can iterate over a Hash using Hash#each method. It is similar to
Array#each method but passes two values to the block parameters, the
key and the value of each element.
Hash#map iterates over a Hash and returns an array with result of
running block for each element of Hash.