liveBook · Manning

Map

As explained in The Well-Grounded Rubyist, Fourth Edition

A key-value data structure that associates keys with corresponding values and preserves the insertion order of its keys.

Suppose you need to look up a state abbreviation from its name. A Ruby hash stores each name with its abbreviation as a key/value pair: `state_hash = { "Connecticut" => "CT", "Delaware" => "DE" }`. Then `state_hash["Connecticut"]` returns `"CT"`. This key-based lookup is the defining job of a map. section 9.3

Unlike an array, whose positions are consecutive integer indexes, a hash lets the programmer choose its keys. Any Ruby object can be a key or value. Each key occurs only once, though different keys may have the same value. Hashes remember the order in which keys were inserted and use that order when iterating over pairs. section 9.1 section 9.3

The common operations fit in a few lines:

  • Create a hash with `{}` or key/value literals. Write `key => value` for any key; the shorter `name: value` form uses a symbol key. `Hash.new` also creates an empty hash. section 9.3.1
  • Assign with `state_hash["New York"] = "NY"` and retrieve with `state_hash["New York"]`. Assigning a different value to an existing key replaces its value without moving the key in insertion order. section 9.3.2
  • Use `fetch(key)` when a missing key should raise an exception; `fetch(key, fallback)` returns the fallback instead. Ordinary `hash[key]` returns `nil` for a missing key unless a default has been configured. section 9.3.2 section 9.3.3

Defaults deserve care. `Hash.new(0)` returns `0` for a missing key, but merely looking up that key does not insert it. A supplied default object is the same object on every such lookup, so mutations to it are shared. A block can produce a fresh result each time; if the missing key should become a real entry, the block must assign it, as in `Hash.new { |hash, key| hash[key] = 0 }`. section 9.3.3

Hashes can also produce other hashes. `select` keeps pairs whose block condition succeeds; `reject` excludes them, and `compact` removes pairs with `nil` values. `invert` exchanges keys and values, but it can discard a pair when two original values become the same new key. Use it only when the values are unique too. section 9.3.5

A hash can package related data for a method call. When it is the final argument, Ruby permits its curly braces to be omitted, giving calls such as `add_to_city_database("New York City", state: "New York", population: 8500000)`. The receiving method still handles a hash and looks up entries by key. For a hash in the first argument position, retain the braces and parenthesize the argument list so Ruby does not read the braces as a block. section 9.3.7

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Works through creation, lookup, defaults, insertion order, and transformations without descending into hash implementation internals.
Examples
Demonstrates state-abbreviation lookup, missing-key defaults, filtering pairs, and passing city data as a final hash argument.
What it assumes
Assumes familiarity with Ruby objects and method calls while teaching hash construction and key-based access from the beginning.
What you can do after
Build it from scratch with Ruby hash literals or constructors, then retrieve, update, and transform key/value pairs.
How it connects
Contrasts hashes with arrays and connects them to symbols, blocks, and method arguments.

Also explained in

Compare how 42 books explain Map →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.