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) β€” raises KeyError if absent (fail loud when the key is required), or fetch(:key, default) for a fallback.
  • dig(:a, :b, :c) β€” safely reach into nested hashes/arrays; returns nil at the first missing link instead of exploding. Perfect for parsing API payloads.
  • Hash.new(0) β€” a default value for missing keys, so counts[:x] += 1 just works.

In an interview, say: "I use fetch when a key is required so a missing one fails loudly at the source, and dig for nested payloads so one missing level returns nil instead of raising three calls deep. Silent nil from [] is how bugs travel far from their cause."