我去了这个页面来了解 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
我理解@@
意味着类变量,但我不明白如何在initialize
方法(构造函数)中创建变量并在另一个方法中使用它,就好像它是类变量一样。这怎么可能?如果您可以在构造函数中定义类变量,那么定义类变量有什么意义?