First, class variables
In Ruby, you can define a class variable for a class, and the value of a class variable is shared by all instances (objects) of the class.
is somewhat similar to static variables in other languages, such as Java, but differs from static variables in Java,
Class variables are private and cannot be accessed outside the class, only through the methods of the class.
Class variables are identified by a @@ symbol (two consecutive @ symbols).
To illustrate:
classDemo @@a= 1defPlus @@a+ = 1Enddef Printputs @@a endend#creating objects, calling methods of objectsdemo1=Demo.newdemo1.PrintDemo1.plusdemo1.PrintDemo2=Demo.newdemo2.PrintDemo2.plusdemo2.Printdemo1.Print
Running the above code, you can see the characteristics of the class variable through the output.
It is important to note that a class variable must be initialized before it can be accessed, so it is generally declared directly in a class, unlike an instance variable that is typically declared in a constructor (or other method).
Because it is declared and initialized in a constructor, creating multiple objects is overwritten by each other. It is declared and initialized directly in the class and is initialized only once.
Ii. Types of methods
In Rbuy, you can define a class method, a bit like a static method in Java. We go directly to the example:
classDemo @@b=2defInitialize @a=1Enddef Printputs @a puts @@b enddefDemo.test#class MethodPuts @a#return Nil@a = 5puts @a puts @@b enddefDemo.test1#class Methodputs @a endend demo=Demo.newdemo.PrintDemo.testDemo.test1demo.Print
Looking at the above code and running results, you will find that the class method has the following characteristics:
1) The definition and reference of a class method require the preceding class name
2) class methods can access class variables
3) The @a referenced in a class method is not an instance variable of the class, but another namespace
Ruby Learning: Class variables and class methods