Comparison of class variables and instance variables in Ruby
This article mainly introduces the comparison between class variables and instance variables in Ruby. This article describes the differences between class variables and instance variables and provides code examples. For more information, see
1. The class variable name starts with @. A Class variable is shared by all instance objects of the class. The instance variable name starts with @, and each instance object has its own different instance variables;
2. class variables must be initialized before use; otherwise, an error is reported during use. If the instance variables are not initialized, nil is returned during use;
3. class variables are private and cannot be directly accessed outside the class. They can be accessed through class methods and instance methods;
Copy the Code as follows:
Class B
@ Number = 11
@ Num = 22
Def my_method # define the instance method
Puts @ number
End
Def self. my_method # define class methods
Puts @ num
End
End
B = B. new ()
Puts B. my_method () # variables of the sort class through the instance method => 11
Puts B. my_method () # Use the class method variables => 22
4. instance variables are private and cannot be directly referenced outside the class. They can be accessed through class methods and instance methods;
Copy the Code as follows:
Class B
@ Num = 11 # This is actually "instance variable of the class"
@ Test = 22
Def my_method # define the instance method
Puts @ num = 33 # It is not in the same scope as @ num defined above => 33
Puts @ test # It is not in the same scope as the @ test defined above, and no initial value is assigned. Therefore, nil is returned.
Puts @ new = 567 # instance variables defined only when the instance runs my_method => 567
End
Def self. my_method # define class methods
Puts @ num # Here @ num is the previously defined @ num => 11
Puts @ test # => 22
End
End
B = B. new ()
B. my_method
Puts "--------------------"
B. my_method