Skip to content

Instantly share code, notes, and snippets.

@koki-h
Last active December 19, 2015 18:19
Show Gist options
  • Save koki-h/5997525 to your computer and use it in GitHub Desktop.
Save koki-h/5997525 to your computer and use it in GitHub Desktop.
例外が発生したらやり直しする。n回まで試行する。試行するまでの待ち時間はsleep_time(秒)で指定する。
class Fixnum
def times_try(sleep_time=0)
count = 0
begin
yield(count)
rescue
if count < self
count += 1
sleep sleep_time
retry
else
raise
end
end
end
end
if $0 == __FILE__
10.times_try(1) do |i|
puts "trial #{i}"
puts "success"
end
10.times_try(1) do
puts "success"
end
10.times_try(1) do |i|
puts "trial #{i}"
raise "aaaa"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment