Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are about six options here: instance variable, class instance variable, class variable, class constant, global variable, global constant. Which to use depends on your needs.</p> <p><strong>Instance Variable</strong> - each MyClass instance gets its own options:</p> <pre><code>class MyClass def initialize @opts = ... end def my_method puts @opts[:thing] end end </code></pre> <p><strong>Class Instance Variable</strong> - single value across the class that can be reassigned:</p> <pre><code>class MyClass @opts = ... class &lt;&lt; self attr_accessor :opts end def my_method puts self.class.opts[:thing] end end </code></pre> <p><strong>Class Variable</strong> - each MyClass <em>and all subclasses</em> share the same value (convenient syntax, but rarely a good idea):</p> <pre><code>class MyClass @@opts = ... def my_method puts @@opts[:thing] end end </code></pre> <p><strong>Class Constant</strong> - single object that may be mutated, but not re-assigned. Easily accessed from this class, accessible from others via <code>MyClass::OPTS</code>:</p> <pre><code>class MyClass OPTS = ... def my_method puts OPTS[:thing] end end </code></pre> <p><strong>Global Variable</strong> - you can only have one of these in your entire app; often global variables are ill-advised, but perhaps appropriate for a standalone application's options:</p> <pre><code>$opts = ... class MyClass def my_method puts $opts[:thing] end end </code></pre> <p><strong>Global Constant</strong> - accessed from many classes, can't be set to a new value, but may be mutated:</p> <pre><code>OPTS = ... class MyClass def my_method puts OPTS[:thing] end end </code></pre>
 

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