Hash Class

A hash is an unordered collection of key-value pairs that look like this: "storm" => "tornado". A hash is similar to an Array, 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 than what you put in—the contents are not ordered like they are in an array.

Creating Hashes

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

months = Hash.new

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

months = Hash.new( "month" ) [or] months = Hash.new "month"

When you access any key in a hash that has a default value, if the key or value doesn’t exist, accessing the hash will return the default value:

months[0] [or] months[72] [or] months[234] # => "month"

Hash also has a class method [], which is called in one of two ways—with ...

Get Ruby Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.