我發現我有很多場合,我有一個通常需要實例化爲「集合」的類。我的解決方案一直是這樣做的:類是使用類方法來「管理」自身實例的好習慣嗎?
class Foo
attr_accessor :bar
def initialize bar
@bar = bar
end
end
class FooCollection
attr_accessor :foos
def initialize
(0.10).each {|n| @foos[n] = Foo.new(n)}
@coolest = 3
end
def coolest
@foos[@coolest]
end
end
我曾考慮過使用這種類型的行爲類方法。我似乎無法下定決心要做到這一點是否更清潔或更混亂。
class Foo
attr_accessor :bar
@@all = []
def self.create_all
(0.10).each {|n| @@all[n] = Foo.new(n)}
@@coolest = 3
end
def self.coolest
@@all[@@coolest]
end
def initialize bar
@bar = bar
end
end
我知道使用類方法創建了它是一個單身的問題,所以如果我需要讓富的多個集合我可能必須進行收集陣列或東西的哈希值。但是,實際上,這些解決方案對我來說都不是「乾淨」的,如果是這種情況,通常會有更好的選擇,我不知道。有一個嗎?
這可能有助於使用實際場景,因爲我無法真正關注您的foobar代碼。 – 2011-05-23 02:47:23
嗯,我是一個新手,但我認爲這將是一個簡單的例子。它只是創建了10個對象的集合,並且具有對象本身無法知道的某種指定。在這種情況下,我選擇了「最酷」。 – 2011-05-23 15:54:08