TIL Enumerable#cycle makes looping sequences easy

Oliver Peate posted on May 16th, 2019

In Ruby an array or finite range raises StopIteration: iteration reached an end once you’ve iterated through the items in the collection. With Enumerable#cycle we can loop around seamlessly.

With an array:

schedule = [:monday, :wednesday, :friday].cycle
# => #<Enumerator: [:monday, :wednesday, :friday]:cycle>

6.times do
  schedule.next # => :monday, :wednesday, :friday, :monday, :wednesday, :friday
end

# or

schedule.take(6) # => [:monday, :wednesday, :friday, :monday, :wednesday, :friday]

With a range:

alphabet = ("a".."z").cycle
# => #<Enumerator: "a".."z":cycle>

24.times do 
  alphabet.next
end

4.times do
  puts alphabet.next
end

# y
# z
# a
# b

What did you learn today?

Write a quick TIL post to reflect on what you've learned.

Write a post