Skip to content

Ruby 2.5 adds KeyError#receiver and KeyError#key

by Atul Bhosale

Ruby 2.5.0 was recently released.

Earlier to Ruby 1.9 Hash#fetch method would raise IndexError for an invalid key. An IndexError is raised when the given index value is invalid.

Ruby

irb(main):001:0> hash = { 'foo' => 'bar' }
irb(main):002:0> hash.fetch('foo')
IndexError: key not found
    from (irb):2:in `fetch'
    from (irb):2
    from :0

KeyError class was introduced in Ruby 1.9 and it inherits from IndexError class. It is raised when the specified key is not found.

Ruby

>> hash = {foo: :bar}
=> {:foo=>:bar}
>> hash.fetch(:baz)
KeyError: key not found: :baz
	from (irb):2:in `fetch'
	from (irb):2
	from /home/atul/.rvm/rubies/ruby-2.4.4/bin/irb:11:in `<main>'

It was proposed that having KeyError#receiver and KeyError#name (or KeyError#key) like NameError, will help to debug and find typo on did_you_mean gem.

Ruby

begin
  h = {foo: 1, bar: 2}
  h.fetch(:bax)
rescue KeyError => e
  p e.name     #=> :bax
  p e.receiver #=> {foo: 1, bar: 2} equal `h`
  end

There was a discussion about what method name is best between name and key. Benoit Daloze suggested that name is more consistent with other error classes such as NameError#name and NoMethodError#name. Having key as method name was approved.

Ruby 2.5.0

Ruby 2.5.0 provides KeyError#receiver and KeyError#key as methods to return details of receiver object and key which was not found.

Ruby

begin
  h = { foo: 1, bar: 2}
  h.fetch(:bax)
rescue KeyError => e
  p e.key      #=> :bax
  p e.receiver #=> {foo: 1, bar: 2}
end

I hope these methods are useful in your future debugging attempts.

More articles

  • Building our own infra using our office hardware

    How we turned a Mac mini and a stack of MacBooks into a self-hosted k3s cluster, moved our apps off a managed platform, and run it all over Tailscale.

    Read more →
  • What Is an AI Harness?

    A harness is the code that sits around an LLM and lets it actually do things: read files, run commands, search the web. The model writes text. The harness turns that text into actions, and the results back into text.

    Read more →

Your competitors are already using AI. The question is how fast you want to unlock the value.

  • Don't know where to start?

    AI is everywhere but it's unclear which investments will actually move your metrics and which are expensive experiments.

  • Your data isn't ready

    Most AI projects fail at the data layer. Pipelines, quality, access all need work before LLMs can deliver value.

  • Internal teams are stretched

    Your engineers are shipping product. They don't have capacity to also become AI specialists with production-grade experience.

  • Legacy systems block everything

    Aging, undocumented codebases make AI integration slow, risky, and expensive. They need to move first.

Don't worry. We've got you covered.

Start with the audit.

Book a free discovery call