Câu hỏi phỏng vấn Ruby
Câu hỏi

Explain redo statement in Ruby

Câu trả lời

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.

How redo Works

The 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.

Example Usage

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

junior

Gợi ý câu hỏi phỏng vấn

junior

Why might you use #each instead of for/in ?

middle

What will be the value of ...

middle

What is the difference between #== and #equal? ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào