liveBook · Manning

Cycle

As explained in The Well-Grounded Rubyist, Fourth Edition

cycle is a Ruby Enumerable method that repeatedly traverses an enumerable object's elements, optionally for a specified number of cycles.

cycle is a Ruby Enumerable method that yields every element repeatedly. Pass an integer to repeat the traversal that many times; omit it for an infinite loop. section 10.5.5

The method can drive a block directly or produce an enumerator through method chaining. Each pass resumes at the collection's beginning after reaching its end. section 10.11.3 section 10.5.5

Use cycle when a collection must provide values beyond its original length:

Repeating a key for XOR

key.each_byte.cycle creates an enumerator that emits the key's bytes repeatedly. A map over the original string takes the next cycling byte for each XOR operation, allowing a short key to cover a longer string. section 10.11.3

Listing 10.6 An exclusive-or method for strings
class String
  def ^(key)             1
    kenum = key.each_byte.cycle      2
    each_byte.map {|byte| byte ^ kenum.next }.pack("C*") 3
  end
end

Inspect a compact implementation that combines each_byte, cycle, next, map, and pack. section 10.11.3

Building a double deck

PlayingCard::Deck.new(2) uses SUITS.cycle(2) and RANKS.cycle(1) to generate two copies of every suit-and-rank combination, producing 104 cards. section 10.5.5

Listing 10.2 Implementing a deck of playing cards
class PlayingCard
  SUITS = %w(clubs diamonds hearts spades)   1
  RANKS = %w(2 3 4 5 6 7 8 9 10 J Q K A)     1
  class Deck
    attr_reader :cards      2
    def initialize(n=1)         3
      @cards = []
      SUITS.cycle(n) do |s|      4
        RANKS.cycle(1) do |r|        5
          @cards << "#{r} of #{s}"       6
        end
      end
    end
  end
end

Inspect the nested cycle calls that construct the deck and control how many times each dimension repeats. section 10.5.5

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains bounded and infinite traversal, enumerator resumption, chaining, and nested use, without detailing implementation internals.
Examples
Demonstrates repeated key bytes for XOR and nested cycles for constructing a 104-card double deck.
What it assumes
Assumes familiarity with collections, blocks, each-like iteration, and enumerators while illustrating chained enumeration from concrete examples.
What you can do after
Apply it via Ruby's Enumerable and Enumerator APIs to repeat finite traversals or supply an explicitly consumed infinite sequence.
How it connects
Connects cycle with Enumerable, Enumerator, each, each_byte, map, and next.

Also explained in

Compare how 2 books explain cycle →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.