Pregunta

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?

¿Fue útil?

Solución

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.

Otros consejos

I am using ruby 1.9.3p0 and have no problems:

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) 

KeyError: key not found: 4
    from (irb):2:in `fetch'
    from (irb):2
    from /home/marek/.rbenv/versions/1.9.3-p0/bin/irb:12:in `<main>'

irb(main):003:0> hash.fetch(1) 
=> "No one"
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top