我正在學習Ruby,我的大腦剛剛凍結。如何在Ruby中爲類變量編寫一個編寫器方法?
在下面的代碼中,我將如何爲'self.total_people'編寫類寫入器方法?我正在「計數」班級「人物」的實例數量。
class Person
attr_accessor :name, :age
@@nationalities = ['French', 'American', 'Colombian', 'Japanese', 'Russian', 'Peruvian']
@@current_people = []
@@total_people = 0
def self.nationalities #reader
@@nationalities
end
def self.nationalities=(array=[]) #writer
@@nationalities = array
end
def self.current_people #reader
@@current_people
end
def self.total_people #reader
@@total_people
end
def self.total_people #writer
#-----?????
end
def self.create_with_attributes(name, age)
person = self.new(name)
person.age = age
person.name = name
return person
end
def initialize(name="Bob", age=0)
@name = name
@age = age
puts "A new person has been instantiated."
@@total_people =+ 1
@@current_people << self
end