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] # BAdding 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) # nilChallenge
MediumA 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>: missingwhendigreturnsnil
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: 39Cheat 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] # 20Assign 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) # nilTry 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.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String Methods OverviewString InterpolationIterating Over StringsSplit and JoinRecap - String Weaver4Blocks, Procs & Lambdas
What is a Block?do..end vs BracesThe yield KeywordBlock ParametersProcs and LambdasRecap - Custom Iterator7Hashes Part 2
Hash.new with DefaultsIterating HashesNested HashesMerging and TransformingRecap - Frequency Counter10Project - Student Records
Project OverviewAdd Student5Enumerable Powerhouse
Select and RejectChaining MapReduce / Injectcount, all?, any?, none?group_by and partitionsort_by, min_by, max_byRecap - Data Pipeline8Advanced Decision Making
Case with Classes & RegexMulti-value whenTernary OperatorInline if / unlessRecap - Grade Classifier