What is the purpose of redo and retry statements in Ruby?

左心房为你撑大大i 提交于 2019-11-30 20:23:49

The idea is that you change something before calling redo or retry, in the hopes that the whatever you were doing will work the second time. I don't have an example for redo, but we have found uses for retry in the application I'm working on. Basically, if you have a bit of code that might fail due to something external (e.g. network), but performing a precondition check every time you run the code would be too expensive, you can use retry in a begin...rescue block. Not sure if that was clear, so I'll get right to the example.

Basically, we have some code that accesses a remote directory using Net:SFTP. The directory should exist, but in some exceptional cases it will not have been made yet. If it's not there, we want to try once to make it. But performing the network access to check if the directory exists every time would be too expensive, especially since it's only in exceptional cases that it won't be there. So we do it as follows:

tried_mkdir = false
begin
  # Attempt to access remote directory
  ...
rescue Net::SFTP::StatusException
  raise if tried_mkdir
  tried_mkdir = true
  # Attempt to make the remote directory
  ...
  retry
end

Use case for redo could be user input checking:

nums = Array.new(5){[rand(1..9), rand(1..9)]}
nums.each do |num1, num2|
  print "What is #{num1} + #{num2}: "
  redo unless gets.to_i == num1 + num2
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!