Explain redo statement in Ruby
Explain redo statement in Ruby
In Ruby, the redo
statement is used to repeat the current iteration of a loop without re-evaluating the loop condition or moving to the next iteration. This keyword is particularly useful in scenarios where you want to retry an operation within the same loop iteration due to a condition that might change during the iteration itself.
redo
WorksThe redo
statement is always used inside a loop. When Ruby encounters redo
, it jumps back to the beginning of the loop block, effectively restarting the loop iteration with the same index or condition. This means that any code after the redo
in the loop will not execute until the condition prompting redo
is resolved, allowing the loop to proceed normally.
Consider a simple use case where you are iterating over a collection of items and performing an operation that might fail and require a retry, such as a network request or a database transaction. Here's a basic example:
items.each do |item|
begin
perform_operation(item)
rescue StandardError => e
puts "Error occurred: #{e}. Retrying..."
redo
end
end
In this example, if perform_operation
raises an exception, the rescue block catches it, logs an error message, and then uses redo
to retry the operation...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào