Created
December 18, 2012 21:25
-
-
Save schneems/4332156 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class Enumerator | |
def try(exception = StandardError) | |
return self unless block_given? | |
yield self.next | |
rescue exception => e | |
@last_try = e and retry unless e.is_a? StopIteration | |
raise @last_try | |
end | |
end | |
3.times.try do |i| | |
puts "foo #{i}" | |
raise "bah" | |
end | |
# foo 0 | |
# foo 1 | |
# foo 2 | |
# RuntimeError: bah | |
3.times.try do |i| | |
puts "foo #{i}" | |
end | |
# foo 0 | |
# => nil |
Ah, just saw your tweet—
we have to raise an exception if you’re beyond your try limit, and self.next raises StopIteration so we store the “real” exception
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why the
@last_try
ivar?