2015-09-06 66 views
0

如何通過將新實例推送到Array來跟蹤類對象,並允許此類數組由另一個類的對象編輯/彈出。在Ruby中跟蹤類對象

例如;

  • 對象「飛機」(平面類)被創建,並推到「在飛行中」稱爲陣列。

  • 對象 '機場'(Airport類)要求它降落和從陣列彈出。

有沒有辦法這樣做,有和/或不使用類變量?

+0

使用工廠方法創建飛機對象,而不是使用'.new'直接創建它們。這個工廠方法除了創建對象之外,還可以將它們註冊到某個數組或任何其他位置 –

回答

1

您可以通過覆蓋Airplane類的initialize方法來做到這一點。事情是這樣的:

class Airplane 
    class << self 
    attr_accessor :in_flight 
    end 
    self.in_flight ||= [] 

    def initialize(*) 
    self.class.in_flight << self 
    super 
    end 

    def land! 
    self.class.in_flight.delete(self) 
    end 
end 

然後,在你的代碼庫中其他任何地方,做這樣的事情:

# We'll just pick a random airplane from the list of those in 
# flight, but presumably you would have some sort of logic around 
# it (already have an Airplane instance somehow, select one from 
# the array according to some criteria, etc). 
airplane = Airplane.in_flight.sample 
airplane.land! 

不知道,這是世界上最偉大的應用程序設計,但它肯定會做如果你的需求很簡單。

+0

這看起來不錯,謝謝 – Harry