Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 134 ยท Collections

Hash Patterns

Learn the everyday hash recipes in Ruby - counting with tally and Hash.new(0), grouping, nested hashes with default procs, inverting, compare_by_identity and insertion order.

Once you know the basic hash methods from Hashes, a handful of recipes cover most of what real programs do with them: count things, group things, index records by a key, build nested structures on demand, and combine several hashes. Learning these as patterns saves you from re-inventing a slow or buggy loop each time.

This lesson walks through the recipes in order: counting, grouping, indexing, nested hashes with default procs, hashes as caches, comparing by identity, and the order guarantee that Ruby makes. Every recipe has a short version that experienced Rubyists write without thinking.

Pattern 1: counting

You have a list and want to know how often each item appears. There are three ways, from most to least explicit.

Ruby Three ways to count

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.

tally is the one to reach for first. It returns a plain hash from each distinct item to its count, in order of first appearance. When you need to count something other than the item itself, map first and then tally, as in words.map(&:length).tally. (Some libraries add a tally_by method, but core Ruby does not have one.)

To find the most common item, combine it with max_by:

Ruby Most common and top three

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 sort key [-n, word] is an array. Ruby compares arrays element by element, so this sorts by count descending and breaks ties alphabetically, which makes the output the same on every run.

Pattern 2: grouping

Counting keeps a number per key. Grouping keeps the items themselves. group_by takes a block that returns the key for each item:

Ruby group_by 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.

group_by is the answer whenever you catch yourself writing "create an empty hash of arrays, loop, append". The manual version of that recipe, using a default block, is worth knowing too because it also works for data that arrives one item at a time:

Ruby Grouping by hand with a default block

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.

Pattern 3: indexing records by a key

If you have a list of records and need to look one up by id again and again, build an index once instead of searching the list every time. index_by is a Rails method; in plain Ruby use to_h, each_with_object or group_by.

Ruby Building an index

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.

A lookup in the index takes the same time for 3 records or 3 million; the find version walks the array and slows down as it grows. When keys can repeat, to_h keeps only the last pair, silently, so use group_by if you must not lose data.

Pattern 4: nested hashes and default procs

A hash of hashes, such as stats[country][city] = population, needs the inner hash to exist before you write into it. Without help you get the infamous NoMethodError on nil:

Ruby Writing into a missing inner hash (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 run ends with main.rb:2:in '<main>': undefined method '[]=' for nil (NoMethodError). The first stats[:uk] returned nil, and nil has no []=. The fix is a default proc that creates the inner hash on demand:

Ruby Auto-vivifying nested hashes

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(&hash.default_proc) hands the same proc to each inner hash, so any depth works. The cost of this convenience is that reads create entries too: asking for probe[:ghost] stores an empty hash. If you only want to look, use dig or key? first. For one level of grouping that is not a problem, which is why the nested default is popular for counters such as Hash.new { |h, k| h[k] = Hash.new(0) }.

Pattern 5: a hash as a cache

The block form of Hash.new is a ready-made memoization table. The block runs once per key and the result is stored:

Ruby Memoizing with 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.

Computing fib[30] takes 31 calls (one per value from 0 to 30) instead of over a million recursive calls. Be careful with ||= when the stored value may legitimately be false or nil: it will recompute every time. Use key? or fetch with a block in that case. Also remember that an unbounded cache is a memory leak; real programs limit its size or lifetime.

Pattern 6: combining and comparing

Ruby Merging, deep merging and diffing

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.

Plain Ruby has no built-in deep merge (Rails adds one), but the block form of merge makes it a six-line recursive method. Array operators & (intersection), | (union) and - (difference) work nicely on key lists.

Pattern 7: inverting and reverse lookup

Ruby invert and reverse lookup

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.

invert is only safe when values are unique. With duplicates, the later key silently wins. Group instead when values can repeat.

Compare by identity

By default a hash treats two keys as the same when they are eql? and have the same hash. For strings, that means equal text. compare_by_identity switches to object identity: only the very same object counts.

Ruby compare_by_identity

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 normal hash holds one entry, because a and b are equal strings. The identity hash holds two, and a fresh "key" literal finds nothing, because it is a different object. Use identity hashes to attach data to objects without changing how those objects compare, for example when tracking which objects you already visited in a graph walk. Symbols and small integers are always the same object, so identity and equality agree for them.

Order is guaranteed

Ruby hashes iterate in insertion order, and that is part of the language rules. Updating the value of an existing key keeps its position; deleting and re-adding a key moves it to the end.

Ruby Insertion order in practice

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.

You can rely on this when printing, serializing and testing. What you should not do is rely on a meaning for the order: it only reflects the history of the hash, not size or importance. Sort explicitly when a particular order is part of the requirement.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which expression gives {"a" => 2, "b" => 1} for %w[a b a]?

    tally counts how often each distinct item appears and returns a hash from item to count. group_by would give arrays of items.
  2. 2. Why does stats = {}; stats[:uk][:london] = 1 fail?

    A missing key returns nil, and calling []= on nil raises NoMethodError. A default proc such as Hash.new { |h, k| h[k] = {} } creates the inner hash.
  3. 3. What is a side effect of Hash.new { |h, k| h[k] = {} } that surprises people?

    The block both computes and stores the default, so even a read adds the key. Use dig or key? when you only want to look.
  4. 4. What happens to the position of a key when you assign a new value to a key that already exists?

    Ruby keeps insertion order, and updating an existing key does not change its place. Only deleting and re-adding moves it to the end.
  5. 5. When is {}.compare_by_identity the right tool?

    An identity hash treats only the very same object as the same key, so two equal but distinct strings get separate entries.

Summary

  • Count with tally, or Hash.new(0) when you build counts incrementally.
  • Group with group_by; partition splits into two lists; transform_values post-processes each group.
  • Build an index with to_h { |r| [r[:id], r] } for fast repeated lookups.
  • Nested hashes need a default proc; remember that reads create keys.
  • Hash.new { ... } is a one-line memoization cache, but unbounded caches grow forever.
  • merge with a block resolves conflicts and makes deep merges simple; invert loses data on duplicate values.
  • Hashes iterate in insertion order, a guarantee of the language.

Next: Sets