Comparison of class variables and instance variables in Ruby _ruby special topics

Source: Internet
Author: User
Tags instance method

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.