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
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 || []
.
This seems to be the way Object#instance_variable_get
works.
I am guessing here you are trying this in IRB. If you open up a prompt and enter self
and self.class
, you can see you are working on an Object
called main
.
But this does only answer the where part of the question (if there was any), not really the why part.