Skip to content

Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

Enumerable#cycle

cycle(n = nil) {|element| ...} → nil
cycle(n = nil) → enumerator

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.

See also #count #detect #compact #drop also in 4.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0