In Ruby, why does an uninitialized instance variable return nil while an uninitialized class variable raises a NameError?
Compare:
@some_uninitialized_variable # => nil
and:
@@some_uninitialized_class_variable # => NameError
My take is the following:
uninitialized local variables return a name error because Ruby doesn't know if its intended to be a local variable or a non-existent method.
if uninitialized class variables returned nil when not defined, it could lead to nasty bugs when the variable was actually assigned the value nil by a distant ancestor. That is, I see this as protecting the coder.
having instance variables default to nil when uninitialized if an oft-used feature: @a = @a || [].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With