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

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

middle

middle

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

junior

What is duck typing and how does it pertain to Ruby?

middle

What is the main difference between procs and lambdas?

senior

When might you encounter a LocalJumpError ?

Bình luận

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

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