instance method
Hash#fetch
(K arg0) -> V
[X] (K arg0, X arg1) -> (V | X)
[X] (K arg0) { (K arg0) -> X } -> (V | X)
fetch(key) → object
fetch(key, default_value) → object
fetch(key) {|key| ... } → object
hash.c
View on GitHub ↗
static VALUE
rb_hash_fetch_m(int argc, VALUE *argv, VALUE hash)
{
VALUE key;
st_data_t val;
long block_given;
rb_check_arity(argc, 1, 2);
key = argv[0];
block_given = rb_block_given_p();
if (block_given && argc == 2) {
rb_warn("block supersedes default value argument");
}
if (hash_stlike_lookup(hash, key, &val)) {
return (VALUE)val;
}
else {
if (block_given) {
return rb_yield(key);
}
else if (argc == 1) {
VALUE desc = rb_protect(rb_inspect, key, 0);
if (NIL_P(desc)) {
desc = rb_any_to_s(key);
}
desc = rb_str_ellipsize(desc, 65);
rb_key_err_raise(rb_sprintf("key not found: %"PRIsVALUE, desc), hash, key);
}
else {
return argv[1];
}
}
}
With no block given, returns the value for the given key, if found;
Example
h = {foo: 0, bar: 1, baz: 2} h.fetch(:bar) # => 1
If the key is not found, returns default_value, if given, or raises KeyError otherwise:
Example
h.fetch(:nosuch, :default) # => :default h.fetch(:nosuch) # Raises KeyError.
With a block given, calls the block with key and returns the block’s return value:
Example
{}.fetch(:nosuch) {|key| "No key #{key}"} # => "No key nosuch"
Note that this method does not use the values of either default or default_proc.
Related: see Methods for Fetching.