Skip to content

Instantly share code, notes, and snippets.

@y13i
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save y13i/10271833 to your computer and use it in GitHub Desktop.
Save y13i/10271833 to your computer and use it in GitHub Desktop.
n回までリトライする
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