O'Reilly logo

The Ruby Programming Language by Yukihiro Matsumoto, David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Hashes

A hash is a data structure that maintains a set of objects known as keys, and associates a value with each key. Hashes are also known as maps because they map keys to values. They are sometimes called associative arrays because they associate values with each of the keys, and can be thought of as arrays in which the array index can be any object instead of an integer. An example makes this clearer:

# This hash will map the names of digits to the digits themselves
numbers = Hash.new     # Create a new, empty, hash object
numbers["one"] = 1     # Map the String "one" to the Fixnum 1
numbers["two"] = 2     # Note that we are using array notation here
numbers["three"] = 3

sum = numbers["one"] + numbers["two"]  # Retrieve values like this

This introduction to hashes documents Ruby’s hash literal syntax and explains the requirements for an object to be used as a hash key. More information on the API defined by the Hash class is provided in Hashes.

Hash Literals

A hash literal is written as a comma-separated list of key/value pairs, enclosed within curly braces. Keys and values are separated with a two-character “arrow”: =>. The Hash object created earlier could also be created with the following literal:

numbers = { "one" => 1, "two" => 2, "three" => 3 }

In general, Symbol objects work more efficiently as hash keys than strings do:

numbers = { :one => 1, :two => 2, :three => 3 }

Symbols are immutable interned strings, written as colon-prefixed identifiers; they are explained in more detail in

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required