This article mainly introduces the comparison between class variables and instance variables in Ruby, this article explains the difference between 4-point class variables and instance variables, and gives the code example, the friend can refer to the following
1. The class variable name begins with @@, and a class variable is shared by all instance objects of this class; the instance variable name begins with the @, each instance object has its own different instance variables;
2, class variables must be initialized before use, otherwise the error will be used, and if the instance variable is not initialized, then return nil when it is used;
3. Class variables are private and cannot be accessed directly outside the class, and can be accessed through class methods and instance methods;
Copy code code as follows:
Class B
@ @number = 11
@ @num = 22
def My_method #定义实例方法
Puts @ @number
End
def Self.my_method #定义类方法
Puts @ @num
End
End
b = B.new ()
Puts B.my_method () #通过实例方法访问类变量 => 11
Puts B.my_method () #通过类方法访问类变量 => 22
4, the instance variable is also private, cannot be directly referenced outside the class, can be accessed through class method and instance method;
Copy code code as follows:
Class B
@num = #实际上这是 instance variable of class
@test = 22
def My_method #定义实例方法
Puts @num = #跟前面定义的 @num is not in one scope =>33
Puts @test #跟前面定义的 @test is not in a scope, does not assign an initial value, and therefore returns nil
Puts @new = 567 #在实例运行my_method时才定义的实例变量 =>567
End
def Self.my_method #定义类方法
Puts @num #这里的 @num is the @num =>11 defined earlier
Puts @test # =>22
End
End
b = B.new ()
B.my_method
Puts "--------------------"
B.my_method