开发者

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

开发者 https://www.devze.com 2023-03-25 11:45 出处:网络
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 equiva

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消