Default Values and Merging
fetch, merge, dig.
Default Values and Merging is a free Ruby Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Ruby Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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)fetch with a Default
Give fetch a second argument as a fallback used only when the key is missing.
h = { name: "Ada" }
puts h.fetch(:age, 0)
puts h.fetch(:name, "Unknown")fetch with a Block
Pass a block to compute the fallback lazily. The block runs only on a miss.
h = {}
puts h.fetch(:x) { "computed default" }Hash with a Default Value
Hash.new(default) returns the default for any missing key instead of nil. The default is shared, so prefer it for simple immutable values.
counts = Hash.new(0)
counts[:a] += 1
counts[:a] += 1
puts counts[:a]
puts counts[:b]Default with a Block
Hash.new { |hash, key| ... } computes a fresh default per key, ideal for grouping into arrays.
groups = Hash.new { |h, k| h[k] = [] }
groups[:fruit] << "apple"
groups[:fruit] << "pear"
puts groups[:fruit].inspectCounting with Defaults
A default of 0 makes word counting simple and clean.
words = ["a", "b", "a", "a"]
count = Hash.new(0)
words.each { |w| count[w] += 1 }
puts countMerging Hashes
merge combines two hashes into a new one. Keys from the second hash win on conflict.
defaults = { color: "red", size: "M" }
user = { color: "blue" }
puts defaults.merge(user)Merge with a Block
Pass a block to merge to resolve conflicts, for example by adding values together.
a = { x: 1, y: 2 }
b = { y: 3, z: 4 }
puts a.merge(b) { |key, old, new| old + new }Safe Nested Access with dig
dig reads through nested hashes safely, returning nil if any level is missing instead of crashing.
data = { user: { address: { city: "London" } } }
puts data.dig(:user, :address, :city)
puts data.dig(:user, :phone, :home).inspectCombining the Tools
Use defaults and merge together to build config from base values plus overrides.
base = { retries: 3, timeout: 30 }
options = base.merge(timeout: 60)
puts options.fetch(:timeout)Quick Check
Check defaults and merging.
Recap
You now handle missing data gracefully:
fetchwith default, block, or strict errorHash.new(0)and block defaults for counting and groupingmergewith conflict blocksdigfor safe nested access
Next course: ranges and Enumerable.
c = Hash.new(0)
c[:hits] += 1
puts c[:hits]Frequently asked questions
Is the “Default Values and Merging” lesson free?
Yes — the full text of “Default Values and Merging” is free to read here on the web, and the Ruby Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Ruby Academy course, upgrade to CoddyKit PRO.
What will I learn in “Default Values and Merging”?
fetch, merge, dig. You practise Ruby Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Ruby Academy?
No prior experience is required. Ruby Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Default Values and Merging” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Ruby Academy lesson?
Yes. Every Ruby Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Symbols vs Strings
- Creating and Reading Hashes
- Hash Iteration
- Default Values and Merging