Search code examples
rubyexceptiondoc

Hash.fetch(not_exist_key) raises IndexError instead of KeyError


In the docs, it says:

fetch(key [, default] ) → obj ; fetch(key) {| key | block } → obj

Returns a value from the hash for the given key. If the key can’t be found, there are several options: With no other arguments, it will raise an KeyError exception; if default is given, then that will be returned; if the optional code block is specified, then that will be run and its result returned.

In my terminal, irb says:

irb(main):001:0> hash = { 1 => "No one", 2 => "gonna", 3 => "fetch me" }
=> {1=>"No one", 2=>"gonna", 3=>"fetch me"}

irb(main):002:0> hash.fetch(4)
IndexError: key not found
    from (irb):2:in `fetch'
    from (irb):2
    from :0

Can you help me explain that?


Solution

  • Seems like you are using an older version of Ruby. According to the 1.8.7 docs it raises an IndexError:

    Returns a value from the hash for the given key. If the key can’t be found, there are several options: With no other arguments, it will raise an IndexError exception; if default is given, then that will be returned; if the optional code block is specified, then that will be run and its result returned.

    Note that KeyError is a subclass of IndexError in Ruby 1.9+, so rescuing IndexError works, too.