我有这段代码执行一系列命令并继续重试,直到达到MAX_RETRIES。我不想一遍又一遍地重复这个命令。这样做有一种优雅的方式吗?
retries = 0
ex = true
MAX_RETRIES = 10
while(retries <= MAX_RETRIES and ex)
begin
#MY CODE HERE
ex = false
rescue
ex = true
end
retries = retries + 1
end
这样的东西?
execute_with_retries do
#CODE HERE
end
execute_with_retries do
#DIFFERENT CODE HERE
end
答案 0 :(得分:2)
定义一个函数并执行块
def execute_with_retries
retries = 0
ex = true
max_retries = 10
while(retries <= max_retries and ex)
begin
yield
ex = false
rescue
ex = true
end
retries = retries + 1
end
end
execute_with_retries { puts "hello" }
execute_with_retries { puts 1/0 }
答案 1 :(得分:0)
MAX_RETRIES = 10
def execute_with_retries(meth)
retries = 0
ex = true
while(retries <= MAX_RETRIES and ex)
begin
public_send(meth)
ex = false
rescue
ex = true
end
retries = retries + 1
end
retries
end
require 'time.h'
def meth
sleep(1)
puts "Time.now in m = #{Time.now}"
puts Time.now - @start < 5 ? "cat"/9 : "dog"
end
@start = Time.now
#=> 2017-12-30 13:39:20 -0800
execute_with_retries(:meth)
Time.now in m = 2017-12-30 13:39:21 -0800
Time.now in m = 2017-12-30 13:39:22 -0800
Time.now in m = 2017-12-30 13:39:23 -0800
Time.now in m = 2017-12-30 13:39:24 -0800
Time.now in m = 2017-12-30 13:39:25 -0800
"dog"
#=> 5