如何将代码传递给函数?

时间:2017-12-29 19:22:44

标签: ruby

我有这段代码执行一系列命令并继续重试,直到达到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

2 个答案:

答案 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 }

我重命名了您的一个变量,您可以阅读here原因。 值得注意的是,Ruby中存在类似的内容,您可以阅读它here

答案 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