Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Instance variables in ruby may be a bit confusing when first learning Ruby, especially if you are accustomed to another OO language like Java. </p> <p>You cannot simply declare an instance variable.</p> <p>One of the most important things to know about instance variables in ruby, apart from the notation with an @ sign prefix, is that <strong>they spring into life the first time they are assigned to</strong>.</p> <pre><code>class Hello def create_some_state @hello = "hello" end end h = Hello.new p h.instance_variables h.create_some_state p h.instance_variables # Output [] ["@hello"] </code></pre> <p>You can use the method <code>Object#instance_variables</code> to list all instance variables of an object.</p> <p>You normally “declare” and initialize all the instance variables in the initialize method. Another way to clearly document which instance variables that should be publicly available is to use the Module methods <code>attr_accessor</code> (read/write), <code>attr_writer</code> (write) and <code>attr_reader</code> (read). These methods will synthesize different accessor methods for the listed instance variable.</p> <pre><code>class Hello attr_accessor :hello end h = Hello.new p h.instance_variables h.hello = "hello" p h.instance_variables # Output [] ["@hello"] </code></pre> <p>The instance variable still isn’t created until it’s assigned to using the synthesized <code>Hello#hello=</code> method.</p> <p>Another important issue, like kch described, is that you need to be aware of the different contexts active when declaring a class. When declaring a class the <em>default receiver (self)</em> in the outermost scope will be the object that represents the class itself. Hence your code will first create a class instance variable when assigning to <code>@hello</code> on the class level.</p> <p>Inside methods <em>self</em> will be the object on which the method is invoked, hence you are trying to print the value of an instance variable with the name <code>@hello</code> in the object, which doesn’t exists (note that it’s perfectly legal to read a non existing instance variable).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload