Skip to content

Instantly share code, notes, and snippets.

@jtprince
Created June 8, 2012 18:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jtprince/2897543 to your computer and use it in GitHub Desktop.
Save jtprince/2897543 to your computer and use it in GitHub Desktop.
NilEnumerator: an enumerator that returns nil instead of a StopIteration exception when it is at the end of the collection
# https://gist.github.com/gists/2897543
# NilEnumerator
#
# an enumerator that yields nil when it is finished. Only implements #next and
# #peak. Would only want to use this if your collection does NOT already include
# nils.
#
# Compare:
#
# # normal iteration requires catching StopIteration
# enum = [1,2,3].each
# begin
# while item=each.next
# p item
# end
# rescue StopIteration
# end
#
# # nil enumerator just yields nil if it is done
# enum = [1,2,3].each.nil_enum # or .to_nil_enum
# while item=enum.next
# p item
# end
#
class NilEnumerator < Enumerator
def initialize(enum)
@enum = enum
end
def next
begin
@enum.next
rescue StopIteration
nil
end
end
def peek
begin
@enum.peek
rescue StopIteration
nil
end
end
end
class Enumerator
def to_nil_enum
NilEnumerator.new(self)
end
alias_method :nil_enum, :to_nil_enum
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment