Module 26 Β· Enumerable, Enumerator & Pattern Matching β Lesson 4 of 6 Β· ~8 min
Hashes & Sets in Anger
Reading hashes safely: fetch, dig, and defaults
hash[:missing] returns nil silently β the source of countless NoMethodError: undefined method for nil. The senior toolkit reads defensively:
fetch(:key)β raisesKeyErrorif absent (fail loud when the key is required), orfetch(:key, default)for a fallback.dig(:a, :b, :c)β safely reach into nested hashes/arrays; returnsnilat the first missing link instead of exploding. Perfect for parsing API payloads.Hash.new(0)β a default value for missing keys, socounts[:x] += 1just works.
In an interview, say: "I use
fetchwhen a key is required so a missing one fails loudly at the source, anddigfor nested payloads so one missing level returns nil instead of raising three calls deep. Silentnilfrom[]is how bugs travel far from their cause."