Default Values and Merging
fetch, merge, dig.
The Problem with nil
Reading a missing key returns nil, which can cause surprises in math or logic. Ruby offers safer ways to handle absence.
h = { a: 1 }
puts h[:b].inspectfetch for Safe Access
fetch returns the value, or raises a clear error if the key is missing. Use it when a key is required.
h = { name: "Ada" }
puts h.fetch(:name)All lessons in this course
- Symbols vs Strings
- Creating and Reading Hashes
- Hash Iteration
- Default Values and Merging