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
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access