Search code examples
rubylanguage-design

Why do some variables being uninitialized cause an error, while others cause a warning?


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?


Solution

  • 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.