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

Explain redo vs. retry usage

Câu trả lời

In Ruby, the redo and retry keywords are used to control the flow of loops and error handling, but they serve different purposes and are used in different contexts.

Redo

The redo statement is used to repeat the current iteration of a loop without re-evaluating the loop condition or fetching the next item in the loop. It is useful when you want to give a loop iteration another chance because some condition was not met or an error occurred, but you believe the issue can be resolved without moving to the next iteration.

For example, if you are processing user input and the input is invalid, you might use redo to repeat the iteration, giving the user another chance to provide valid input:

ruby Copy
(0..5).each do |i|
  puts "Value: #{i}"
  redo if i > 2  # This creates an infinite loop if not handled correctly
end

In this example, once i exceeds 2, the loop will continuously redo the iteration where i is 3, creating an infinite loop unless additional logic is added to break out of the loop[3][4][5].

Retry

The retry statement, on the other hand, is used to start the entire loop or block from the beginning. It is typically used in error handling where an exception might occur, and you want to attempt the entire operation again. For instance, if a network operation fails due to a temporary issue, you might want to retry the entire operation hoping that the connection issue resolves itself.

Here’s an example using retry in a loop with exception handling:

ruby Copy
begin
  1.upto(5) do |i|
    puts "Attempt number #{i}"
    raise "Error" if i == 3
  end
rescue
  retry
end

In this example, when i equals 3, an error is raised, triggering the rescue block which then calls retry. This starts the entire loop over from the first iteration. Note that without a mechanism to br...

middle

middle

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

entry

What is a class in ruby?

junior

What is the return value for ...

entry

What is the highest level in the object model?

Bình luận

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

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