我有一個員工類,我存儲員工詳細信息,如年齡,生日和獲得的積分。如何訪問所有創建的對象和更新屬性
class Employee
attr_accessor :id, :dob, :points
def initialize
@id = id
@dob = dob
@points = points
end
def tranfer_points
# Access both employee objects and add points to one and remove points from other
end
end
emp_one = Employee.new(1,"2 Jan 1990",400)
emp_two = Employee.new(2,"12 Jan 1986",700)
emp_two.transfer()
我想知道維護所有創建對象的最佳做法是什麼,以便我可以將點從一個員工轉移到其他員工。
我應該在這裏使用類變量,這是一個很好的解決方案,這是一個標準的做法嗎?
像下面
class Employee
@@all_employee = Hash.new
attr_accessor :id, :dob, :points
def initialize
@id = id
@dob = dob
@points = points
add_all_employee
end
def add_all_employee
@@all_employee[id] = self
end
def tranfer_points(i,points)
b = @@all_employee[i]
self.balance -= points
b.points += points
end
end
任何幫助這裏將不勝感激。謝謝。
沒有數據庫? – scorix
嗨scorix,是的沒有數據庫 –
爲什麼你需要一個'員工'類?不會簡單的'Hash'實例足夠嗎? – mudasobwa