Method: Hash#fetch
- Defined in:
- ext/enterprise_script_service/mruby/mrbgems/mruby-hash-ext/mrblib/hash.rb
#fetch(key, none = NONE, &block) ⇒ Object
call-seq:
hsh.fetch(key [, default] ) -> obj
hsh.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 <code>KeyError</code> exception; if <i>default</i> is
given, then that will be returned; if the optional code block is
specified, then that will be run and its result returned.
h = { "a" => 100, "b" => 200 }
h.fetch("a") #=> 100
h.fetch("z", "go fish") #=> "go fish"
h.fetch("z") { |el| "go fish, #{el}"} #=> "go fish, z"
The following example shows that an exception is raised if the key
is not found and a default value is not supplied.
h = { "a" => 100, "b" => 200 }
h.fetch("z")
<em>produces:</em>
prog.rb:2:in 'fetch': key not found (KeyError)
from prog.rb:2
171 172 173 174 175 176 177 178 179 180 181 182 183 |
# File 'ext/enterprise_script_service/mruby/mrbgems/mruby-hash-ext/mrblib/hash.rb', line 171 def fetch(key, none=NONE, &block) unless self.key?(key) if block block.call(key) elsif none != NONE none else raise KeyError, "Key not found: #{key.inspect}" end else self[key] end end |