Chúng ta đã nói về retry keyword khi discuss retrying after exceptions. Little-known counterpart redo work similarly, nhưng re-runs loop iterations thay vì whole blocks.
redo keyword
Như học trong Academy article trước, retry cho retry piece of code trong block:
begin
puts "Iteration"
raise
rescue
retry
end
Ví dụ in "Iteration" ra console trước raise exception. Rescue block execute, gọi retry start block again từ đầu. Result chương trình endlessly print Iteration. redo keyword cho achieve similar effect khi dùng loops. Useful khi cần retry while iterating.
10.times do |i|
puts "Iteration #{i}"
redo if i > 2
end
Sẽ print:
$ ruby redo.rb
Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 3
Iteration 3
...
Notice iteration count stays same? Step back execution đến start của loop. Variant dùng retry print exact same output:
10.times do |i|
begin
puts "Iteration #{i}"
raise if i > 2
rescue
retry
end
end
Dùng redo implement retrying trong loop. Ví dụ sau queue of jobs. Chúng return :success hoặc :failure. Keep re-running same iteration loop cho đến job succeeds.
[job_1, job_2, job_3, job_4].each do |job|
redo unless job.call == :success
end
Ruby 1.8
Behavior của retry và redo changed giữa Ruby 1.8 và 1.9. Chúng dùng restart loop iteration, nhưng both khác cách. Từ 1.9, retry chỉ work với begin/rescue block và redo chỉ work within loops.
next keyword
Nếu muốn move đến next iteration loop, thay vì move back start current one, dùng next.
10.times do |i|
puts "Iteration #{i}"
next if i > 2
puts "Iteration done"
end
Sẽ print:
$ ruby next.rb
Iteration 0
Iteration done
Iteration 1
Iteration done
Iteration 2
Iteration done
Iteration 3
Iteration 4
...
See iteration counter keeps incrementing? Trong most cases dùng next là what you want. Look at redo nếu cần loop run exact number of times hoặc need error handling khi iterate over array.
Hy vọng bạn học mới về redoing iterations in loops và would love to know thoughts bạn về bài này (hoặc other ones AppSignal Academy series). Đừng ngần ngại let us know what you think, hoặc Ruby subjects bạn muốn learn more.