Chapter 6. Hashes

Hashes and arrays are the two basic “aggregate” data types supported by most modern programming lagnguages. The basic interface of a hash is similar to that of an array. The difference is that while an array stores items according to a numeric index, the index of a hash can be any object at all.

Arrays and strings have been built into programming languages for decades, but built-in hashes are a relatively recent development. Now that they’re around, it’s hard to live without them: they’re at least as useful as arrays.

You can create a hash by calling Hash.new or by using one of the special syntaxes Hash[] or {}. With the Hash[] syntax, you pass in the initial elements as comma-separated object references. With the {} syntax, you pass in the initial contents as comma-separated key-value pairs:

empty = Hash.new                            # => {}
empty ={}                                   # => {}
numbers = { :two => 2, :eight => 8}         # => {:two=>2, :eight=>8}
numbers = Hash[:two, 2, :eight, 8]          # => {:two=>2, :eight=>8}

In Ruby 2.1, a new syntax was introduced for declaring hashes that saves you a few characters:

    numbers = { two: 2, eight: 8 }              # => {:two=>2, :eight=>8}

Once the hash is created, you can do hash lookups and element assignments using the same syntax you would use to view and modify array elements:

numbers[:two]                              # => 2
numbers[:ten] = 10                         # => 10
numbers                                    # => {:two=>2, :eight=>8, :ten=>10}

You can get an array containing the keys or values of a hash with Hash#keys or Hash#values. You can get the entire hash as ...

Get Ruby Cookbook, 2nd Edition now with O’Reilly online learning.

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