Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Ruby

Làm Chủ Điều Khiển Vòng Lặp Ruby: redo, retry, Và next Giải Thích

Chúng ta đã nói về keyword retry khi thảo luận về retry sau exceptions. Counterpart ít known hơn redo hoạt động tương tự, nhưng re-run loop iterations thay vì whole blocks.

Keyword redo

Như đã học ở bài Academy trước, retry cho phép retry piece of code trong block:

begin
  puts "Iteration"
  raise "Error!"
rescue
  retry
end

Ví dụ này print "Iteration" ra console trước khi raise exception. Rescue block executes, gọi retry và start block again từ beginning. Điều này dẫn đến program endlessly printing Iteration. Keyword redo cho phép achieve similar effect khi dùng loops. Hữu ích khi bạn cần retry while iterating.

5.times do |i|
  puts "Iteration #{i}"
  redo if i == 2
end

Điều này sẽ print:

Iteration 0
Iteration 1
Iteration 2
Iteration 2
Iteration 2
... (infinite loop tại iteration 2)

Chú ý iteration count stays the same? Nó step back execution đến start của loop. Variant này dùng retry sẽ print exact same output:

i = 0
begin
  puts "Iteration #{i}"
  raise "Error!" if i == 2
  i += 1
rescue
  retry if i == 2
end

Bạn có thể dùng redo để implement retrying trong loop. Trong ví dụ tiếp theo, chúng ta có queue của jobs. Chúng return :success hoặc :failure. Chúng ta keep re-running same iteration của loop cho đến khi job succeeds.

jobs = [:failure, :failure, :success, :failure, :success]

jobs.each do |job|
  result = job
  redo if result == :failure
  puts "Job succeeded!"
end

# Output:
# Job succeeded!
# Job succeeded!
# Job succeeded!

Keyword next

Nếu bạn muốn move to next iteration của loop, opposed to move back to start của current one, bạn dùng next.

5.times do |i|
  next if i == 2
  puts "Iteration #{i}"
end

Điều này sẽ print:

Iteration 0
Iteration 1
Iteration 3
Iteration 4

Nhìn iteration counter keeps incrementing? Trong most cases dùng next là what you want. Look at redo nếu bạn cần loop chạy exact number of times hoặc cần error handling khi iterating over array.

Chúng ta hy vọng bạn learned something new về redoing iterations in loops và would love to know what you thought of this article (hoặc any other ones in AppSignal Academy series). Please don't hesitate to let us know what you think, hoặc nếu bạn có Ruby subjects muốn learn more about.

Làm Chủ Điều Khiển Vòng Lặp Ruby: redo, retry, Và next Giải Thích

Thijs Cadier

Chief Technology Officer & Co-Founder. Thijs đôi khi missing for months on end để work on infrastructure. Makes sure billions of requests handled correctly. Best drummer của company.

Tất cả bài viết của Thijs Cadier