Menu
Coddy logo textTech

Nested Hashes

Part of the Logic & Flow section of Coddy's Ruby journey — lesson 35 of 56.

A hash value can itself be a hash. This nested shape is how Ruby code typically represents structured records, a single hash keyed by id (or name), where each value carries its own fields:

students = {
  "Alice" => { age: 20, grade: "A" },
  "Bob"   => { age: 22, grade: "B" }
}

To reach a nested value, chain the lookups:

puts students["Alice"][:age]    # 20
puts students["Bob"][:grade]    # B

Adding a new field to one of the inner hashes works the same way:

students["Alice"][:major] = "Math"
puts students["Alice"]
# {age: 20, grade: "A", major: "Math"}

To safely read from a nested hash that might be missing a key at any level, dig walks the chain and returns nil if anything along the way is missing:

students.dig("Alice", :grade)   # "A"
students.dig("Cara",  :grade)   # nil
challenge icon

Challenge

Medium

A nested inventory hash is given: each top-level key is a department, each inner key an item, and each inner value the stocked quantity (an integer).

Read one line of input: a comma-separated list of department/item lookup paths.

For each path, in order, use dig to resolve it. Print either:

  • <department>/<item>: <qty> when the path exists
  • <department>/<item>: missing when dig returns nil

After printing every line, also print one summary line:

Total inventory: <sum>

The total is the sum of every quantity across every department in the original hash. Use nested iteration (each department, then each item).

For input fruits/apples,meat/beef,fruits/dragonfruit,dairy/milk, the output is:

fruits/apples: 12
meat/beef: 7
fruits/dragonfruit: missing
dairy/milk: 9
Total inventory: 39

Cheat sheet

Nested hashes store hashes as values inside another hash:

students = {
  "Alice" => { age: 20, grade: "A" },
  "Bob"   => { age: 22, grade: "B" }
}

Chain lookups to access nested values:

students["Alice"][:age]    # 20

Assign to add or update a nested field:

students["Alice"][:major] = "Math"

Use dig to safely traverse nested keys — returns nil if any key is missing:

students.dig("Alice", :grade)   # "A"
students.dig("Cara",  :grade)   # nil

Try it yourself

inventory = {
  fruits: { apples: 12, bananas: 4 },
  meat:   { beef: 7, chicken: 5 },
  dairy:  { milk: 9, cheese: 2 }
}
lookups = gets.chomp.split(",")

# TODO: for each lookup, dig and print qty or 'missing'.
#       Then print 'Total inventory: <sum>' across all items.
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow