Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 134 ยท Collections

Hashes

Learn Ruby hashes from scratch - symbol keys, reading with [] and fetch, default values, iteration, merge, delete, dig, transform_values and the pitfalls that trip up beginners.

An array finds things by position: "give me item number 3". A hash finds things by name: "give me the value stored under :email". It is a collection of key-value pairs, and it is the second most used data structure in Ruby after the array. Configuration, parsed JSON, database rows, counters, lookup tables and keyword arguments are all hashes (or look like them).

Ruby hashes remember the order in which keys were first inserted, and that order is guaranteed. Lookups are fast: finding a key takes roughly the same time whether the hash holds ten entries or ten million. This lesson covers creating hashes, reading values safely, the several ways to supply a default, iterating, combining and changing hashes, and digging into nested data. Hash Patterns continues with counting, grouping and default procs.

Creating a hash

Ruby Hash literals and symbol keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The short form name: "Ada" creates a symbol key (:name). Symbols are small, immutable names that are cheap to compare (see Symbols), so they are the standard choice for keys when you know the names while writing the code. When keys come from data (user input, a file, a database), they are usually strings or integers, and you write them with =>.

puts person and p person print the same text here, because a hash prints in its inspect form either way. Since Ruby 3.4 that format shows {name: "Ada", age: 36} for symbol keys and {"alice" => 90}, with spaces around the arrow, for other keys.

You can also build a hash from other data. to_h converts a list of pairs, and Hash[] and zip are common companions:

Ruby Building hashes from other data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The last example uses hash shorthand: { x:, y: } means { x: x, y: y }. It is handy when a local variable already carries the right name.

Reading values: [], fetch and friends

The square-bracket form returns nil for a missing key. That is convenient, and also the source of many bugs, because nil flows on silently until something breaks far from the cause.

Ruby Missing keys: [] versus fetch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

fetch has three behaviors: it returns the value if the key exists, the default (or the block's result) if you gave one, and raises an error otherwise. The error is exactly what you want for a setting that must be present:

Ruby fetch without a default (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The second fetch stops the script with main.rb:3:in 'Hash#fetch': key not found: :port (KeyError). The message names the missing key, which makes the bug easy to find. Use [] when absence is normal, and fetch when absence is a bug.

Two more readers are worth knowing: values_at(:a, :b) returns several values at once, and fetch_values(:a, :b) does the same but raises KeyError if any key is missing.

Defaults with Hash.new

A hash can answer for missing keys itself. Pass a value to Hash.new and it is returned whenever a key is absent:

Ruby Default values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Hash.new(0) is the classic counter: counts[ch] += 1 expands to counts[ch] = counts[ch] + 1, and the read of a missing key gives 0. The block form receives the hash and the key, so it can calculate a value and store it. That is a one-line memoization table.

There is one famous trap. A default value is a single object shared by every missing key. If it is mutable, all keys end up sharing it:

Ruby The shared default trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

In the wrong version << mutates the shared default array and never stores anything in the hash, so the hash stays empty while groups[:other] suddenly contains both words. Use the block form whenever the default is an array, a string or another hash.

Adding, changing and deleting

Ruby Changing a hash

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Methods that end in ! (or are named delete_if, clear, store) change the hash itself. Their cousins without those marks (reject, select, merge) return a new hash and leave the original alone. Keys must not be mutated after use, so prefer immutable keys such as symbols, numbers and frozen strings. (A string used as a key is copied and frozen for you.)

Iterating

each yields a key and a value. The pair arrives as a two-element array, which block parameters unpack automatically.

Ruby Iterating over a hash

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Everything in Enumerable works on hashes, because a hash is a collection of pairs. Note two details. map returns an array, so call .to_h when you want a hash again. And with each_with_index the pair is wrapped in parentheses (name, price) because there are two things to unpack: the pair, and the index.

Transforming and filtering

Hashes have their own versions of the common iterators, and these return hashes:

Ruby select, transform_values, filter_map and friends

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

transform_values and transform_keys are the idiomatic way to change one side of every pair. slice keeps the keys you name, and except (Ruby 3.0) drops them. select and reject return hashes, while filter_map, partition, group_by and find return arrays (or pairs).

Merging hashes

merge combines two hashes into a new one. When both have the same key, the second hash wins, unless you pass a block to decide:

Ruby merge and conflicts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The pattern defaults.merge(options) is everywhere in Ruby code: start from sensible defaults and let the caller override some of them.

Nested data: dig

JSON-like data nests hashes inside hashes inside arrays. Reading it with chained [] raises NoMethodError the moment one level is nil. dig walks the path and returns nil as soon as something is missing:

Ruby Safe nested access with dig

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The failing chain prints Error: undefined method '[]' for nil. dig is shorter and safer. For nested required data, use chained fetch (user.fetch(:address).fetch(:city)) so that a missing level raises a clear KeyError.

Checking contents and comparing

Ruby Queries on a hash

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Two hashes are == when they have the same keys with equal values. The order of insertion does not matter for equality, even though it matters for iteration.

Pitfalls and good habits

  • Missing key versus nil value. h[:x] cannot tell the two apart. Use key? or fetch when the difference matters.
  • Modifying while iterating. Adding or removing keys inside each raises RuntimeError ("can't add a new key into hash during iteration"). Build a new hash instead, or iterate over hash.keys (a copy).
  • Mutable keys. If you mutate an array used as a key, the hash can no longer find it. Use frozen or immutable keys.
  • String versus symbol keys. {"a" => 1}[:a] is nil. Data parsed from JSON has string keys unless you ask for symbols (see JSON). Pick one convention at your boundary and convert once.
  • Printing for debugging. Use p or pp (pretty print) rather than puts, which hides the structure of nested data.
  • Large lookups. Need to ask "is this item in the list?" thousands of times? Turn the list into a hash or a Set, whose lookup does not slow down with size, instead of calling include? on an array.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does { a: 1 }[:b] return?

    The bracket reader returns nil for a missing key (unless the hash has a default). Only fetch raises KeyError.
  2. 2. You want a setting that must exist and should raise a clear error otherwise. Which call fits best?

    fetch raises KeyError with the missing key in the message. The other calls silently give nil or a boolean.
  3. 3. What is wrong with groups = Hash.new([]) followed by groups[:a] << 1?

    The default array is one shared object. << changes it but never stores it under :a. Use Hash.new { |h, k| h[k] = [] } instead.
  4. 4. Two hashes are merged with a.merge(b) and both contain the key :x. Which value ends up in the result?

    The hash passed as argument wins unless you give merge a block to resolve the conflict.
  5. 5. What does data.dig(:user, :address, :city) do when data[:user] is nil?

    dig stops at the first nil and returns nil, which is what makes it safe for optional nested data.

Summary

  • A hash maps keys to values and keeps insertion order. Symbol keys use the short key: value syntax; other keys use =>.
  • [] returns nil for missing keys; fetch raises KeyError or accepts a default or block.
  • Hash.new(0) makes counters; use the block form for mutable defaults to avoid sharing one object.
  • each, select, reject, transform_values, slice, except and merge cover most everyday work.
  • merge lets the second hash win unless you pass a conflict block.
  • dig reads nested data safely; chain fetch when each level is required.

Next: Hash Patterns