Skip to content

Instantly share code, notes, and snippets.

@mmagm
Created April 17, 2013 14:41
Show Gist options
  • Save mmagm/5404854 to your computer and use it in GitHub Desktop.
Save mmagm/5404854 to your computer and use it in GitHub Desktop.
class InfiniteCycleEnumerator
def self.enum(num)
Enumerator.new do |y|
idx = 0
loop do
y << idx % num
idx = idx + 1
end
end
end
end
class InfiniteArrayEnumerator
def self.enum(array)
Enumerator.new do |y|
cycle = InfiniteCycleEnumerator.enum(array.length)
loop do
y << array[cycle.next]
end
end
end
end
# examples
enumerator = InfiniteArrayEnumerator.enum(['one', 'two', 'free'])
# => #<Enumerator: #<Enumerator::Generator:0x0000000c723790>:each>
enumerator.next
# => "one"
enumerator.next
# => "two"
enumerator.next
# => "free"
enumerator.next
# => "one"
enumerator.next
# => "two"
enumerator.next
# => "free"
enumerator.next
# => "one"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment