Method: Array#fetch

Defined in:
array.c

#fetch(index) ⇒ Object #fetch(index, default_value) ⇒ Object #fetch(index) {|index| ... } ⇒ Object

Returns the element of self at offset index if index is in range; index must be an integer-convertible object.

With the single argument index and no block, returns the element at offset index:

a = [:foo, 'bar', 2]
a.fetch(1)   # => "bar"
a.fetch(1.1) # => "bar"

If index is negative, counts from the end of the array:

a = [:foo, 'bar', 2]
a.fetch(-1) # => 2
a.fetch(-2) # => "bar"

With arguments index and default_value (which may be any object) and no block, returns default_value if index is out-of-range:

a = [:foo, 'bar', 2]
a.fetch(1, nil)  # => "bar"
a.fetch(3, :foo) # => :foo

With argument index and a block, returns the element at offset index if index is in range (and the block is not called); otherwise calls the block with index and returns its return value:

a = [:foo, 'bar', 2]
a.fetch(1) {|index| raise 'Cannot happen' } # => "bar"
a.fetch(50) {|index| "Value for #{index}" } # => "Value for 50"

Related: see Methods for Fetching.

Overloads:

  • #fetch(index) {|index| ... } ⇒ Object

    Yields:



2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
# File 'array.c', line 2039

static VALUE
rb_ary_fetch(int argc, VALUE *argv, VALUE ary)
{
    VALUE pos, ifnone;
    long block_given;
    long idx;

    rb_scan_args(argc, argv, "11", &pos, &ifnone);
    block_given = rb_block_given_p();
    if (block_given && argc == 2) {
        rb_warn("block supersedes default value argument");
    }
    idx = NUM2LONG(pos);

    if (idx < 0) {
        idx +=  RARRAY_LEN(ary);
    }
    if (idx < 0 || RARRAY_LEN(ary) <= idx) {
        if (block_given) return rb_yield(pos);
        if (argc == 1) {
            rb_raise(rb_eIndexError, "index %ld outside of array bounds: %ld...%ld",
                        idx - (idx < 0 ? RARRAY_LEN(ary) : 0), -RARRAY_LEN(ary), RARRAY_LEN(ary));
        }
        return ifnone;
    }
    return RARRAY_AREF(ary, idx);
}