一般来说,避免“未定义的方法‘some_method’”对于 nil:NilClass”在红宝石中
Ruby 的鸭式打字很棒,但这是它让我很恼火的一种方式。我将运行一些长时间运行的文本处理脚本或某些东西,几个小时后,一些意外的情况最终导致脚本因变量变为 而以
NoMethodError
退出无。
现在,一旦发生这种情况,通常很容易修复,但如果我能够更好地预测这些错误,或者至少更优雅地处理这些类型的错误,那就更好了。很抱歉问题含糊不清,但这种类型的错误对我来说经常发生,我想知道是否有一个好的方法来避免它。
Ruby 是否有一些与此类“类型错误”相关的最佳实践?
Ruby's duck-typing is great, but this is the one way that it bites me in the ass. I'll have some long running text-processing script or something running, and after several hours, some unexpected set of circumstances ends up causing the script to exit with at NoMethodError
due to a variable becoming nil
.
Now, once it happens, it's usually an easy fix, but it would be nicer if I could predict these better, or at least handle these types of errors more gracefully. Sorry for the vagueness of the question, but this type of error just happens too often to me and I wonder if there's a good way to avoid it.
Is there some best practice related to these kinds of "type errors" for Ruby?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查找按合同设计。它在许多编程范例中都很有用,但是当您没有编译器来帮助您捕获此类错误(禁止参数使用特定类型的值)时,它尤其有用。
本质上,DbC 允许您对参数做出假设。它允许您(除了一个地方之外)跳过保证这一假设成立的普通检查。
Look up Design by Contract. It's useful in many programming paradigms, but it's particularly useful when you don't have a compiler to help you catch these sort of errors, of forbidding particular sorts of values for a parameter.
In essence, DbC allows you to make an assumption about a parameter. It allows you (in all but one place) to skip the mundane checks that guarantee this assumption to hold.
Object.nil 怎么样?
What about Object.nil?