Ruby 中重做和重试语句的目的是什么? [英] What is the purpose of redo and retry statements in Ruby?

查看:37
本文介绍了Ruby 中重做和重试语句的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能想到的用于 redo 的唯一用例是用于诸如写入套接字或从数据库读取之类的操作,但如果这些操作失败一次,后续尝试很可能也会失败,因此它对我来说仍然似乎有点毫无意义,至于 retry 我真的想不出任何有用的情况.

The only use case I can think of for redo would be for operations like writing to a socket or reading from a database, but if these fail once, subsequent attempts will most likely also fail so it still seems a bit pointless to me and as for retry I can't really think of any case where it would be useful.

这对我来说似乎毫无意义,因为我不知道或使用 Ruby,但我渴望有一天能创造出一种很棒的语言,所以我想至少知道一些最流行语言的设计背后的推理在那里.

This might only seem meaningless to me since I don't know or use Ruby, but I aspire to create an awesome language one day so I would like to at least know the reasoning behind the design of some of the most popular languages out there.

推荐答案

这个想法是你在调用 redoretry 之前改变一些东西,希望无论什么你正在做的将工作第二次.我没有 redo 的示例,但我们在我正在处理的应用程序中发现了 retry 的用途.基本上,如果您有一些代码可能由于外部因素(例如网络)而失败,但是每次运行代码时执行前提条件检查的成本太高了,您可以在代码中使用 retrybegin...rescue 块.不确定这是否清楚,所以我会直接进入示例.

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.

基本上,我们有一些使用 Net:SFTP 访问远程目录的代码.目录应该存在,但在某些特殊情况下还没有创建.如果它不存在,我们想尝试一次来实现它.但是每次都执行网络访问以检查目录是否存在会太昂贵,特别是因为只有在特殊情况下它才会不存在.所以我们这样做:

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

这篇关于Ruby 中重做和重试语句的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆