Created
June 8, 2012 18:47
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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