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:
- Use cycle(n) for a known number of complete traversals. section 10.5.5
- Use cycle without an argument when a consumer will stop the enumerator explicitly. section 10.11.3 section 10.5.5
- Treat cycle(1) as an each-like single traversal. section 10.5.5
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

