Last active
August 29, 2015 13:58
-
-
Save y13i/10271833 to your computer and use it in GitHub Desktop.
n回までリトライする
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
class Integer | |
def attempts error_class = StandardError, &block | |
fail "Block is required." unless block_given? | |
1.upto self do |i| | |
begin | |
return yield i | |
rescue error_class => e | |
raise e if i == self | |
next | |
end | |
end | |
end | |
end | |
# example | |
300.attempts ZeroDivisionError do |i| | |
puts "Attempt ##{i}" | |
score = rand 101 | |
puts "Score: #{score}" | |
num = score > 95 ? 1 : 0 | |
1 / num | |
end | |
# Attempt #1 | |
# Score: 20 | |
# Attempt #2 | |
# Score: 49 | |
# Attempt #3 | |
# Score: 92 | |
# Attempt #4 | |
# Score: 7 | |
# Attempt #5 | |
# Score: 43 | |
# Attempt #6 | |
# Score: 18 | |
# Attempt #7 | |
# Score: 84 | |
# Attempt #8 | |
# Score: 96 | |
# => 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment