Skip to content

Instantly share code, notes, and snippets.

@pierre
Last active December 26, 2015 03:59
Show Gist options
  • Save pierre/7089539 to your computer and use it in GitHub Desktop.
Save pierre/7089539 to your computer and use it in GitHub Desktop.
Ruby Enumerator to Java Iterator
class EnumeratorIterator
def initialize(delegate)
@buffer = []
# We expect an Enumerable or Enumerator
@delegate = delegate.is_a?(Enumerable) ? delegate.to_enum : delegate
_next
end
def has_next
!@next.nil?
end
def next
prev = @next
_next
prev
end
def remove
raise NotImplementedError.new
end
private
def _next
@next = @buffer.shift
return unless @next.nil?
@next = @delegate.next rescue nil
return if @next.nil?
if @next.is_a? Enumerable
@buffer += @next.to_a
else
@buffer << @next
end
_next
end
end
a = EnumeratorIterator.new([1,2,3,4,5, [6,7], 8, [9, 10]].to_enum)
while a.has_next
puts a.next
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment