Things We Can Do with Hashes
Practice calling some important methods on hashes.
We'll cover the following...
We'll cover the following...
Methods of the Hash class
The main purpose of a Hash object is to look a value up by a key. However, there are a few more things we can do with hashes. Below is a list of methods supported by the Hash class. Don’t be too concerned with memorizing all of them.
The merge method
We can merge two hashes by calling the merge method:
The fetch method
The fetch method does just the same as the square bracket lookup ([]) discussed before, but it raises an error if the key isn’t defined:
Notice that line 2 outputs “eins”, but line 3 raises an error.
The keys method
The keys method returns an array with all the keys that the hash knows:
The length and size methods
The length and size methods both indicate the number of key/value pairs contained in the hash: