End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Array#cycle
array.cycle {|element| ... } → nil
array.cycle(count) {|element| ... } → nil
array.cycle → new_enumerator
array.cycle(count) → new_enumerator
array.c
View on GitHub ↗
static VALUE
rb_ary_cycle(int argc, VALUE *argv, VALUE ary)
{
long n, i;
rb_check_arity(argc, 0, 1);
RETURN_SIZED_ENUMERATOR(ary, argc, argv, rb_ary_cycle_size);
if (argc == 0 || NIL_P(argv[0])) {
n = -1;
}
else {
n = NUM2LONG(argv[0]);
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;
}
When called with positive Integer argument count and a block, calls the block with each element, then does so again, until it has done so count times; returns nil:
Example
output = [] [0, 1].cycle(2) {|element| output.push(element) } # => nil output # => [0, 1, 0, 1]
If count is zero or negative, does not call the block:
Example
[0, 1].cycle(0) {|element| fail 'Cannot happen' } # => nil [0, 1].cycle(-1) {|element| fail 'Cannot happen' } # => nil
When a block is given, and argument is omitted or nil, cycles forever:
Example
# Prints 0 and 1 forever. [0, 1].cycle {|element| puts element } [0, 1].cycle(nil) {|element| puts element }
When no block is given, returns a new Enumerator:
Example
[0, 1].cycle(2) # => #<Enumerator: [0, 1]:cycle(2)> [0, 1].cycle # => # => #<Enumerator: [0, 1]:cycle> [0, 1].cycle.first(5) # => [0, 1, 0, 1, 0]