Quick Answer

Accessing non-existent hash keys

Understanding the Issue

Ruby raises KeyError when accessing missing keys with fetch() or when trying to reference undefined keys with certain methods.

The Problem

This code demonstrates the issue:

Ruby Error
# Problem: Missing key
h = { a: 1 }
h.fetch(:b) # KeyError

The Solution

Here's the corrected code:

Ruby Fixed
# Solution 1: Default value
h.fetch(:b, 0) # => 0

# Solution 2: Safe access
h[:b] || "default"

# Solution 3: has_key? check
h[:b] if h.key?(:b)

Key Takeaways

Always handle missing keys gracefully.