Well, first of all... it's a really good idea to explain how @@
variables work exactly.
@@
variables are class variables that can be accessed on the instance context, say for example:
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 # => "Say whaat?"
However this type of variables will incur also in the following result:
class OtherKlass < Klass; end
Klass.new.my_klass_variable = "Howdy"
# Note this is a different instance, and from the child class
OtherKlass.new.my_klass_variable # => "Howdy"
Crazy behavior indeed. Another way to create Class variables, is defining instance variables on a method that starts with self.
. For example:
class Klass
def self.my_class_method
@class_var = "This is a class var"
end
end
Why a @
for class variables as well? Remember that Klass
in this is an instance of the Class
class, this will have its own instance variables, that at the end will be class variables for instances of Klass
.
Klass.class # => Class
Klass.instance_of?(Class) # => true
k = Klass.new
k.class # => Klass
k.instance_of?(Klass) # => true
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:
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
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.