Skip to content

Instantly share code, notes, and snippets.

@porras
Created June 14, 2016 17:37
Show Gist options
  • Save porras/be4aee02b15e16bb61d1c9ec9210426c to your computer and use it in GitHub Desktop.
Save porras/be4aee02b15e16bb61d1c9ec9210426c to your computer and use it in GitHub Desktop.
class CachedEnumerable
include Enumerable
def initialize(wrapped = nil)
@enumerator = case wrapped
when Enumerator
wrapped
when Enumerable
wrapped.to_enum
when NilClass
Enumerator.new { |e| yield(e) }
else
raise ArgumentError, "#{self.class.name} must be initialized with an Enumerator, an Enumerable or a block, not a #{wrapped.class.name}"
end
@cache = []
end
def each(&block)
@cache.each(&block)
while next_item = @enumerator.next
@cache << next_item
block.call(next_item)
end
rescue StopIteration
# nothing
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment