Skip to content

Instantly share code, notes, and snippets.

@h3h
Created August 15, 2014 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save h3h/f15668c345715c58670c to your computer and use it in GitHub Desktop.
Save h3h/f15668c345715c58670c to your computer and use it in GitHub Desktop.
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