Chapter 7. Hashes

A hash is an unordered collection of key-value pairs that look like this: "storm" => "tornado". A hash is similar to an Array (see Chapter 6), but instead of a default integer index starting at zero, the indexing is done with keys that can be made up from any Ruby object. In other words, you can use integer keys just like an Array, but you also have the option of using any Ruby object as a key, even an Array! (Hashes are actually implemented as arrays in Ruby.)

Hashes can be accessed by keys or by values, but usually by keys, which must be unique. If you attempt to access a hash with a key that does not exist, the method will return nil (unless the hash has a default value). The key-value pairs in a hash are not stored in the same order that they are inserted (the order you placed them in the hash), so don’t be surprised if the contents of a hash look different from what you put in—the contents are not ordered the same way as in an array.

Creating Hashes

Like arrays, there are a variety of ways to create hashes. You can create an empty hash with the new class method.

months = Hash.new

You can test to see if a hash is empty with empty?:

months.empty? # => true

or how big it is with length or size:

months.length
months.size # => 0

You can also use new to create a hash with a default value—which is otherwise just nil—like this:

months = Hash.new( "month" )

or like this:

months = Hash.new "month"

When you access any key in a hash that has a default value, if the key or value doesn’t ...

Get Learning 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.