rubyruby-2.6

Undeclared instance variables default to nil?


Due to some sloppy coding on my part, I've noticed that undeclared instance variables seem to evaluate nil where undeclared local variables do not. Is this default nill value for instance variables intended behavior that I can exploit (like with a conditional to check whether the variable has been set true) or is this just a quirk that should be left alone?

2.6.6 :001 > puts @test

 => nil 
2.6.6 :002 > puts test
Traceback (most recent call last):
        2: from (irb):2
        1: from (irb):2:in `test'
ArgumentError (wrong number of arguments (given 0, expected 2..3))

Solution

  • Per the Ruby doc:

    Instance variables of ruby do not need declaration. This implies a flexible structure of objects. In fact, each instance variable is dynamically appended to an object when it is first referenced.

    https://ruby-doc.org/docs/ruby-doc-bundle/UsersGuide/rg/instancevars.html

    You can also get a list of all previously defined instance variables:

    ClassName.instance_variables
    

    or

    a = ClassName.new 
    a.instance_variables #specific to instance