cycle(...)
public
Calls block for each element
repeatedly n times or forever if none or nil is given. If a
non-positive number is given or the array is empty, does nothing. Returns
nil if the loop has finished without getting interrupted.
a = ["a", "b", "c"]
a.cycle {|x| puts x }
a.cycle(2) {|x| puts x }
Show source
/*
* call-seq:
* ary.cycle {|obj| block }
* ary.cycle(n) {|obj| block }
*
* Calls <i>block</i> for each element repeatedly _n_ times or
* forever if none or nil is given. If a non-positive number is
* given or the array is empty, does nothing. Returns nil if the
* loop has finished without getting interrupted.
*
* a = ["a", "b", "c"]
* a.cycle {|x| puts x }
* a.cycle(2) {|x| puts x }
*
*/
static VALUE
rb_ary_cycle(argc, argv, ary)
int argc;
VALUE *argv;
VALUE ary;
{
long n, i;
VALUE nv = Qnil;
rb_scan_args(argc, argv, "01", &nv);
RETURN_ENUMERATOR(ary, argc, argv);
if (NIL_P(nv)) {
n = -1;
}
else {
n = NUM2LONG(nv);
if (n <= 0) return Qnil;
}
while (RARRAY(ary)->len > 0 && (n < 0 || 0 < n--)) {
for (i=0; i<RARRAY(ary)->len; i++) {
rb_yield(RARRAY(ary)->ptr[i]);
}
}
return Qnil;
}