我去了this page瞭解Ruby類。該網頁上的代碼是這樣的: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
方法(構造函數)一個變量,並使用它裏面的另一種方法,如果是一個類變量。這怎麼可能?如果你可以在構造函數中定義它,那麼定義類變量有什麼意義呢?
它在構造函數中如何定義類變量? – yngccc 2013-04-24 19:38:51
@yngum'@ cust_id = id'。我想這不是定義類變量,但我的問題更多的是如何在一個函數中定義一個變量並在該函數之外使用它。 – Richard 2013-04-24 19:41:49
'@ cust_id'是一個實例變量,您顯然可以在任何實例方法中使用實例變量。 – yngccc 2013-04-24 19:45:20