📜  Ruby 重做和重试语句

📅  最后修改于: 2022-05-13 01:54:50.264000             🧑  作者: Mango

Ruby 重做和重试语句

在 Ruby 中, Redo 语句用于重复循环的当前迭代。 redo 总是在循环内使用。 redo 语句重新启动循环而不再次评估条件。

# Ruby program of using redo statement
  
#!/usr/bin/ruby
restart = false
  
# Using for loop
for x in 2..20
    if x == 15
        if restart == false
  
            # Printing values
            puts "Re-doing when x = " + x.to_s
            restart = true
  
            # Using Redo Statement
            redo
        end
    end
    puts x
end

输出:

2
3
4
5
6
7
8
9
10
11
12
13
14
Re-doing when x = 15
15
16
17
18
19
20

在上面的示例中,重做语句适用于x = 15

重试语句:

要从头开始重复整个循环迭代,请使用重试语句。重试总是在循环内使用。

示例 #1:

# Ruby program of retry statement
  
# Using do loop
10.times do |i|
  begin
    puts "Iteration #{i}"
    raise if i > 2
  rescue
  
    # Using retry
    retry
  end
end

输出:

Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 3
Iteration 3
...

示例 #2:

# Ruby program of retry statement
def geeks
  attempt_again = true
  p 'checking'
  begin
  
    # This is the point where the control flow jumps
    p 'crash'
    raise 'foo'
      rescue Exception => e
        if attempt_again
          attempt_again = false
  
      # Using retry
      retry       
    end
  end
end