APIdock / Ruby
/
method

fetch

ruby latest stable - Class: Array
fetch(p1, p2 = v2)
public

Tries to return the element at position index, but throws an IndexError exception if the referenced index lies outside of the array bounds. This error can be prevented by supplying a second argument, which will act as a default value.

Alternatively, if a block is given it will only be executed when an invalid index is referenced.

Negative values of index count from the end of the array.

a = [ 11, 22, 33, 44 ]
a.fetch (1) #=> 22
a.fetch (-1) #=> 44
a.fetch (4, 'cat') #=> "cat"
a.fetch (100) { |i| puts "#{i} is out of bounds" }
 #=> "100 is out of bounds"
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);
}

AltStyle によって変換されたページ (->オリジナル) /