fill(p1 = v1, p2 = v2)
public
The first three forms set the selected
elements of self (which may be the entire array) to obj.
A start of nil is equivalent to zero. A length of nil is equivalent to
self.length. The last three forms fill the array with the value of the block. The
block is passed the absolute index of each element to be filled. Negative values of
start count from the end of the
array.
a = [ "a", "b", "c", "d" ]
a.fill("x")
a.fill("z", 2, 2)
a.fill("y", 0..1)
a.fill {|i| i*i}
a.fill(-2) {|i| i*i*i}
Show source
static VALUE
rb_ary_fill(int argc, VALUE *argv, VALUE ary)
{
VALUE item, arg1, arg2;
long beg = 0, end = 0, len = 0;
VALUE *p, *pend;
int block_p = FALSE;
if (rb_block_given_p()) {
block_p = TRUE;
rb_scan_args(argc, argv, "02", &arg1, &arg2);
argc += 1; /* hackish */
}
else {
rb_scan_args(argc, argv, "12", &item, &arg1, &arg2);
}
switch (argc) {
case 1:
beg = 0;
len = RARRAY_LEN(ary);
break;
case 2:
if (rb_range_beg_len(arg1, &beg, &len, RARRAY_LEN(ary), 1)) {
break;
}
/* fall through */
case 3:
beg = NIL_P(arg1) ? 0 : NUM2LONG(arg1);
if (beg < 0) {
beg = RARRAY_LEN(ary) + beg;
if (beg < 0) beg = 0;
}
len = NIL_P(arg2) ? RARRAY_LEN(ary) - beg : NUM2LONG(arg2);
break;
}
rb_ary_modify(ary);
if (len < 0) {
return ary;
}
if (beg >= ARY_MAX_SIZE || len > ARY_MAX_SIZE - beg) {
rb_raise(rb_eArgError, "argument too big");
}
end = beg + len;
if (RARRAY_LEN(ary) < end) {
if (end >= ARY_CAPA(ary)) {
ary_resize_capa(ary, end);
}
rb_mem_clear(RARRAY_PTR(ary) + RARRAY_LEN(ary), end - RARRAY_LEN(ary));
ARY_SET_LEN(ary, end);
}
if (block_p) {
VALUE v;
long i;
for (i=beg; i<end; i++) {
v = rb_yield(LONG2NUM(i));
if (i>=RARRAY_LEN(ary)) break;
RARRAY_PTR(ary)[i] = v;
}
}
else {
p = RARRAY_PTR(ary) + beg;
pend = p + len;
while (p < pend) {
*p++ = item;
}
}
return ary;
}