The blog post Uninitialized variables points out that uninitialized class variables, local variables and constants cause an exce开发者_运维问答ption (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?
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:
@var ||= 'default_value'
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
and method_missing
provide hooks to handle their absence. For example, I believe Rails uses const_missing
to load classes at run time.
精彩评论