Ruby Newbie homepage Ruby Newbie homepage

How to use

Quick guide

Official content
Returns the value for the given key, if found.
h = {foo: 0, bar: 1, baz: 2}
h.fetch(:bar) # => 1
If key is not found and no block was given, returns default_value:
{}.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:
{}.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.
 
               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];
        }
    }
}
            

Was this page useful?