Quick Answer

Handle missing hash keys.

Understanding the Issue

Modern Ruby raises KeyError instead of returning nil for missing keys, encouraging explicit handling.

The Problem

This code demonstrates the issue:

Ruby Error
hash = {name: "John"}
hash[:age] # KeyError

The Solution

Here's the corrected code:

Ruby Fixed
# Solution 1: Use fetch with default
age = hash.fetch(:age, 30) # => 30

# Solution 2: Check key existence
if hash.key?(:age)
  hash[:age]
end

# Solution 3: Rescue KeyError
begin
  value = hash.fetch(:missing_key)
rescue KeyError => e
  puts "Key not found: #{e.key}"
end

# Solution 4: Default proc
hash_with_default = Hash.new { |h,k| h[k] = "default_#{k}" }

Key Takeaways

Explicitly handle missing keys rather than relying on nil returns.