Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why in Ruby do uninitialized instance variables return nil, but uninitialized class variables raise an error?

Tags:

ruby

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
like image 431
enocom Avatar asked Feb 21 '15 21:02

enocom


1 Answers

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 || [].

like image 68
Cary Swoveland Avatar answered Nov 20 '22 17:11

Cary Swoveland