Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Well, first of all... it's a really good idea to explain how <code>@@</code> variables work exactly. </p> <p><code>@@</code> variables are class variables that can be accessed on the instance context, say for example:</p> <pre><code>class Klass def my_klass_variable=(str) # self here points to an instance of Klass @@my_klass_variable = str end def my_klass_variable @@my_klass_variable end end Klass.new.my_klass_variable = "Say whaat?" # Note this is a different instance Klass.new.my_klass_variable # =&gt; "Say whaat?" </code></pre> <p>However this type of variables will incur also in the following result:</p> <pre><code>class OtherKlass &lt; Klass; end Klass.new.my_klass_variable = "Howdy" # Note this is a different instance, and from the child class OtherKlass.new.my_klass_variable # =&gt; "Howdy" </code></pre> <p>Crazy behavior indeed. Another way to create Class variables, is defining instance variables on a method that starts with <code>self.</code>. For example:</p> <pre><code>class Klass def self.my_class_method @class_var = "This is a class var" end end </code></pre> <p>Why a <code>@</code> for class variables as well? Remember that <code>Klass</code> in this is an <em>instance</em> of the <code>Class</code> class, this will have its own instance variables, that at the end will be class variables for instances of <code>Klass</code>.</p> <pre><code>Klass.class # =&gt; Class Klass.instance_of?(Class) # =&gt; true k = Klass.new k.class # =&gt; Klass k.instance_of?(Klass) # =&gt; true </code></pre> <p>This is more safe for class variables (as they will have one copy of the variable, and not a shared one with child classes as well), and will behave as you are expecting to behave when using your example:</p> <pre><code>module Ammunition def self.included(base) base.class_eval do @ammo = [bullets] # where bullets come from any way? end end def self.unload p @ammo end end class Tank include Ammunition # Probably you meant that instead of Packagable @ammo += [shells] # I think you meant @ammo instead of @a end class Airplane include Ammunition # Probably you meant that instead of Packagable @ammo += [missiles, photon_torpedoes] # I think you meant @ammo instead of @a end </code></pre> <p>This code as pointed by others won't work (given there is no shells, missiles nor photo_torpedoes), but I think you can figure it out how to make it work by yourself.</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