ruby - Hash.fetch(not_exist_key) raises IndexError instead of KeyError -
in docs, says:
fetch(key [, default] ) → obj ; fetch(key) {| key | block } → obj
returns value hash given key. if key can’t found, there several options: no other arguments, raise keyerror exception; if default given, returned; if optional code block specified, run , result returned.
in 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 (irb):2:in `fetch' (irb):2 :0
can me explain that?
seems using older version of ruby. according 1.8.7 docs raises indexerror
:
returns value hash given key. if key can’t found, there several options: no other arguments, raise indexerror exception; if default given, returned; if optional code block specified, run , result returned.
note keyerror
subclass of indexerror
in ruby 1.9+, rescuing indexerror
works, too.
Comments
Post a Comment