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:

ruby Copy
items.each do |item|
  begin
    perfor...
junior

junior

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

junior

What are two uses of the splat operator?

junior

Are instance methods public or private?

middle

What are two uses of ranges?

Bình luận

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

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