Skip to content

End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Enumerable#cycle

enum.cycle(n=nil) { |obj| block } → nil
enum.cycle(n=nil) → an_enumerator

Calls block for each element of enum repeatedly n times or forever if none or nil is given. If a non-positive number is given or the collection is empty, does nothing. Returns nil if the loop has finished without getting interrupted.

Enumerable#cycle saves elements in an internal array so changes to enum after the first pass have no effect.

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

Example
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.
See also #count #detect #collect_concat #drop also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1