APIdock / Ruby
/
method

cycle

ruby latest stable - Class: Array
cycle(p1 = v1)
public

Calls the given block for each element n times or forever if nil is given.

Does nothing if a non-positive number is given or the array is empty.

Returns nil if the loop has finished without getting interrupted.

If no block is given, an Enumerator is returned instead.

a = ["a", "b", "c"]
a.cycle  { |x| puts x } # print, a, b, c, a, b, c,.. forever.
a.cycle (2) { |x| puts x } # print, a, b, c, a, b, c.
static VALUE
rb_ary_cycle(int argc, VALUE *argv, VALUE ary)
{
 long n, i;
 VALUE nv = Qnil;
 rb_scan_args(argc, argv, "01", &nv);
 RETURN_SIZED_ENUMERATOR(ary, argc, argv, rb_ary_cycle_size);
 if (NIL_P(nv)) {
 n = -1;
 }
 else {
 n = NUM2LONG(nv);
 if (n <= 0) return Qnil;
 }
 while (RARRAY_LEN(ary) > 0 && (n < 0 || 0 < n--)) {
 for (i=0; i<RARRAY_LEN(ary); i++) {
 rb_yield(RARRAY_AREF(ary, i));
 }
 }
 return Qnil;
}

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