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 so开发者_如何学Gomething 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?
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.
What about Object.nil?
精彩评论