Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
CircularEnumerator
# Utility converter to make a circular enumerator, wrapping around to the
# beginning of a list after it has exhausted all entries.
#
# Example:
#
# >> e = CircularEnumerator([1,2,3,4,5])
# => #<Enumerator: [1, 2, 3, 4, 5]:each>
#
# >> 10.times.map { e.next }
# => [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
#
def CircularEnumerator(enumerable)
e = enumerable.to_enum
class << e
def next
super
rescue StopIteration
rewind
retry
end
end
e
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.