Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
Enumerable#cycle
(?::Integer n) { (E arg0) -> untyped } -> ::NilClass
(?::Integer n) -> ::Enumerator[E, ::NilClass]
cycle(n = nil) {|element| ...} → nil
cycle(n = nil) → enumerator
enum.c
View on GitHub ↗
static VALUE
enum_cycle(int argc, VALUE *argv, VALUE obj)
{
VALUE ary;
VALUE nv = Qnil;
rb_len_t n;
rb_len_t i, len;
rb_check_arity(argc, 0, 1);
RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_cycle_size);
if (!argc || NIL_P(nv = argv[0])) {
n = -1;
}
else {
n = NUM2LEN(nv);
if (n <= 0) return Qnil;
}
ary = rb_ary_new();
RBASIC_CLEAR_CLASS(ary);
rb_block_call(obj, id_each, 0, 0, cycle_i, ary);
len = RARRAY_LEN(ary);
if (len == 0) return Qnil;
while (n < 0 || 0 < --n) {
for (i=0; i<len; i++) {
enum_yield_array(RARRAY_AREF(ary, i));
}
}
return Qnil;
}
When called with positive integer argument n and a block, calls the block with each element, then does so again, until it has done so n times; returns nil:
Example
a = [] (1..4).cycle(3) {|element| a.push(element) } # => nil a # => [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4] a = [] ('a'..'d').cycle(2) {|element| a.push(element) } a # => ["a", "b", "c", "d", "a", "b", "c", "d"] a = [] {foo: 0, bar: 1, baz: 2}.cycle(2) {|element| a.push(element) } a # => [[:foo, 0], [:bar, 1], [:baz, 2], [:foo, 0], [:bar, 1], [:baz, 2]]
If count is zero or negative, does not call the block.
When called with a block and n is nil, cycles forever.
When no block is given, returns an Enumerator.