def print_var
print "In module #{self.class.name}: #{@variable}\n"
end
def print_class_var
print "In module class-variable #{self.class.name}: #{@@class_variable}\n"
end
def set_variables(var, cvar)
@variable = var
@@class_variable = cvar
end
end
class A
include Variables
def initialize(var, cvar)
@variable = var
@@class_variable = cvar
end
def print_variables
print "variables: #{@variable}, #{@@class_variable}\n"
end
def self.print_class_a_variables
print "Class '#{self.class.name}' variable: #{@@class_variable}\n"
end
a.print_class_var # fail: :8:in print_class_var': uninitialized class variable @@class_variable in Variables (NameError) # Why? I set '@@class_variable in 'initialize'
a.set_variables(12, 33) # Once again set '@@class_variavle'
Then why in 'set_variables' (module Variables) is set @@class_variable for class 'A', appropriates to a class variable value? The second call (at the end of program) of a.print_variables already displays the changed values.
I guess this is where "the Standard" comes in.
Anyone who can check ISO/IEC 30170 ? I don't have ;-)
The current behavior is conforming to ISO/IEC 30170.
In "11.5.4.5 Class variables" of ISO/IEC 30170:
A class-variable-identifier is evaluated as follows:
a) Let N be the class-variable-identifier. Let C be the first class or module in the list at the top of [class-module-list] which is not a singleton class.
b) Let CS be the set of classes which consists of C and all the superclasses of C. Let MS be the set of modules which consists of all the modules in the included module list of all classes in CS. Let CM be the union of CS and MS.
c) If a binding with name N exists in the set of bindings of class variables of only one of the classes or modules in CM, let V be the value of the binding.
d) If more than two classes or modules in CM have a binding with name N in the set of bindings of class variables, let V be the value of one of these bindings. Which binding is selected is implementation-defined.
e) If none of the classes or modules in CM has a binding with name N in the set of bindings of class variables, let S be a direct instance of the class Symbol with name N and raise a direct instance of the class NameError which has S as its name attribute.
f) The value of the class-variable-identifier is V.
, where [class-module-list] is a stack of lists who represent the basically same information as Module.nesting.