KeyError
RubyERRORNotableCollection

Hash key not found

Quick Answer

Use Hash#fetch with a default value, or Hash#[] and handle nil explicitly.

What this means

Raised when a key is not found in a Hash. Hash#fetch raises KeyError by default for missing keys, whereas Hash#[] returns nil. KeyError is a subclass of IndexError.

Why it happens
  1. 1Calling Hash#fetch with a key that does not exist and no default provided
  2. 2ENV#fetch for an environment variable that is not set

Fix

Provide a default to fetch

Provide a default to fetch
config = { host: 'localhost' }
port = config.fetch(:port, 3000)            # => 3000
db   = config.fetch(:db) { 'development' }  # block form

Why this works

A default value or block prevents KeyError when the key is absent.

Code examples
Hash#fetch raises KeyErrorruby
{a: 1}.fetch(:b)
# KeyError: key not found: :b
ENV fetch missing variableruby
ENV.fetch('DATABASE_URL')
# KeyError: key not found: "DATABASE_URL"
Rescue KeyErrorruby
begin
  value = config.fetch(:required_key)
rescue KeyError => e
  puts "Missing config: #{e.key}"
end
Sources
Official documentation ↗

Ruby Core Documentation

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Ruby errors