Hashes

Although arrays provide a good way of indexing a collection of items by number, sometimes it would be more convenient to index them in some other way. If, for example, you were creating a collection of recipes, it would be more meaningful to have each recipe indexed by name, such as “Rich Chocolate Cake” and “Coq au Vin,” rather than by numbers.

Ruby has a class that lets you do just that, called a hash. This is the equivalent of what some other languages call a dictionary or associative array. Just like a real dictionary, each entry is indexed by a unique key (in a real-life dictionary, this would be a word) that is associated with a value (in a dictionary, this would be the definition of the word).

Creating Hashes

Just like an array, you ...

Get The Book of Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.