Skip to content

Instantly share code, notes, and snippets.

@schneems
Created December 18, 2012 21:25
Show Gist options
  • Save schneems/4332156 to your computer and use it in GitHub Desktop.
Save schneems/4332156 to your computer and use it in GitHub Desktop.
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
@nz
Copy link

nz commented Dec 18, 2012

Why the @last_try ivar?

rescue exception => e
  retry unless e.is_a? StopIteration
  raise e
end

@nz
Copy link

nz commented Dec 18, 2012

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