每次创建对象时都会使用实例变量,如果它们未初始化,则它们具有nil 值,并且需要初始化类变量,如果没有,它们会产生错误。
最大的原因之一是子分类。如果您计划子类化,则需要使用类变量。这是一个讨论两者以及何时使用什么的链接:
http://www.railstips.org/blog/archives/2006/11/18/class-and-instance-variables-in-ruby/
这是一个有助于描述两者之间区别的链接:
http://www.tutorialspoint.com/ruby/ruby_variables.htm
这是我刚刚提到的网站上的一些代码,显示两者都在使用:
#!/usr/bin/ruby
class Customer
@@no_of_customers=0
def initialize(id, name, addr)
@cust_id=id
@cust_name=name
@cust_addr=addr
end
def display_details()
puts "Customer id #@cust_id"
puts "Customer name #@cust_name"
puts "Customer address #@cust_addr"
end
def total_no_of_customers()
@@no_of_customers += 1
puts "Total number of customers: #@@no_of_customers"
end
end
# Create Objects
cust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya")
cust2=Customer.new("2", "Poul", "New Empire road, Khandala")
# Call Methods
cust1.total_no_of_customers()
cust2.total_no_of_customers()