Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
Hash#fetch
hash.fetch(key) → object
hash.fetch(key, default_value) → object
hash.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];
}
}
}
Returns the value for the given key, if found.
Example
h = {foo: 0, bar: 1, baz: 2} h.fetch(:bar) # => 1
If key is not found and no block was given, returns default_value:
Example
{}.fetch(:nosuch, :default) # => :default
If key is not found and a block was given, yields key to the block and returns the block’s return value:
Example
{}.fetch(:nosuch) {|key| "No key #{key}"} # => "No key nosuch"
Raises KeyError if neither default_value nor a block was given.
Note that this method does not use the values of either default or default_proc.