为什么某些未初始化的变量会导致错误,而另一些则导致警告?
博文未初始化的变量指出未初始化的类变量、局部变量和常量会导致异常(经过method_missing
或其等效项),而未初始化的全局变量和实例变量只会导致警告。
是否存在导致异常和仅导致警告的逻辑?
The blog post Uninitialized variables points out that uninitialized class variables, local variables and constants cause an exception (after going through method_missing
or their equivalent), while uninitialized global variables and instance variables only cause a warning.
Is there a logic to which ones cause an exception, and which cause only a warning?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的猜测是,当异常在元编程中可能有用时,就会提供异常。如果您发现全局变量或实例变量丢失,您可以轻松地实例化它——我经常看到这样的说法:
不需要任何花哨的东西。
对于类、其他常量和方法,检查它们是否已定义并内联使用它们会更尴尬。异常(以及诸如 const_missing 和 method_missing 等相关方法提供了钩子来处理它们的缺失。例如,我相信 Rails 使用 const_missing 来加载类在运行时。
My guess is that exceptions are provided when they might be useful in metaprogramming. You can easily instantiate a global variable or instance variable if you find it is missing -- I see the idiom often:
No need for anything fancy.
For classes, other constants and methods, it's more awkward to check if they are defined and use them inline. The exceptions (and the associated methods like
const_missing
andmethod_missing
provide hooks to handle their absence. For example, I believe Rails usesconst_missing
to load classes at run time.