Skip to content
instance method

Array#cycle

(?::int? n) { (Elem) -> void } -> nil
(?::int? n) -> ::Enumerator[Elem, nil]
cycle(count = nil) {|element| ... } → nil
cycle(count = nil) → new_enumerator

With a block given, may call the block, depending on the value of argument count; count must be an integer-convertible object, or nil.

When count is positive, calls the block with each element, then does so repeatedly, 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]

When 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 count is nil, cycles forever:

Example
# Prints 0 and 1 forever.
[0, 1].cycle {|element| puts element }
[0, 1].cycle(nil) {|element| puts element }

With no block given, returns a new Enumerator.

Related: see Methods for Iterating.

See also #count #delete #concat #delete_at also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0