APIdock / Ruby
/
method

fill

ruby latest stable - Class: Array
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 the length of the array.

The last three forms fill the array with the value of the given block, which is passed the absolute index of each element to be filled.

Negative values of start count from the end of the array, where -1 is the last element.

a = [ "a", "b", "c", "d" ]
a.fill ("x") #=> ["x", "x", "x", "x"]
a.fill ("z", 2, 2) #=> ["x", "x", "z", "z"]
a.fill ("y", 0..1) #=> ["y", "y", "z", "z"]
a.fill  { |i| i*i } #=> [0, 1, 4, 9]
a.fill (-2) { |i| i*i*i } #=> [0, 1, 8, 27]
static VALUE
rb_ary_fill(int argc, VALUE *argv, VALUE ary)
{
 VALUE item = Qundef, arg1, arg2;
 long beg = 0, end = 0, len = 0;
 if (rb_block_given_p()) {
 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);
 }
 ary_mem_clear(ary, RARRAY_LEN(ary), end - RARRAY_LEN(ary));
 ARY_SET_LEN(ary, end);
 }
 if (item == Qundef) {
 VALUE v;
 long i;
 for (i=beg; i<end; i++) {
 v = rb_yield(LONG2NUM(i));
 if (i>=RARRAY_LEN(ary)) break;
 ARY_SET(ary, i, v);
 }
 }
 else {
 ary_memfill(ary, beg, len, item);
 }
 return ary;
}

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