- Difference between
@@variable and self.variable in scope of main.
As we probably know, @@variable is a class variable.
@@variable will attach itself to the class of self.class. The class of main is Object.
To demonstrate:
self # => main
self.class # => Object
@@variable = "variable"
self.class.class_variables # => [:@@variable]
object.class_variables # => [:@@variable]
Be aware, this means every object will have access to @@variable.
String.class_variables # => [:@@variable]
and modifying that variable at the top level will also change its value for all objects.
self.variable will give a NoMethodError, as there are no getters or setters for it. If you were to define a getter and setter, however ...
class Object
class << self
attr_accessor :variable
end
end
self.variable = "variable" # => "variable"
- Difference between
@@variable and self.variable in scope of a class.
@@variable will be have the same way as above, except now instead of class Object, we're applying it to whatever class we're currently in.
But now, self.variable will apply to a Class Instance Variable. This is the sort of variable that's most commonly referred to as Class Variables or Static Variables in other languages (ie. it is only accessible to that class, and not its children). It is the same as having a @variable at the class's top level.
class T
@some = "some"
class << self
attr_accessor :variable
end
self.variable = "variable"
end
T.instance_variables # => [:@some, :@variable]
- Difference between
@@variable and self.variable in scope of a method.
@@variable behaves exactly as above -- it's still referring to the class we are defining the method of.
But now self.variable refers to an instance variable, not the Class's instance.
class T
attr_accessor :variable
def initialize
self.variable = "variable"
end
end
instance = T.new
instance.instance_variables
instance.variable # => "variable"
- "How many variables are there? And under what scope?"
In your example, there are 5 variables (assuming proper getters/setters have been created):
- Class variable
@@variable belonging to Object
- Instance variable
main.variable belonging to the instance main of class Object
- Class variable
@@variable belonging to A
- Class Instance variable
A.variable belonging to class A
- Instance variable
@variable belonging to any instances of A.