我需要一個類似哈希的類,雖然不一定與所有的哈希方法。我已經讀過,將類核心類如Hash進行子類化並不是一個好主意。不管這是否屬實,做這種事情的最佳做法是什麼?子類核心Ruby類如哈希
# (a) subclass Hash, add new methods and instance variables
class Book < Hash
def reindex
@index = .....
end
end
# (b) create a new class from scratch, containing a hash,
# and define needed methods for the contained hash
class Book
def initialize(hash)
@data = hash
end
def []=(k,v)
@data[k] = v
end
# etc....
def reindex
@index = ....
end
# (c) like (b) but using method_missing
# (d) like (b) but using delegation
我意識到Ruby有完成既定任務的方法不止一種,但是否有任何一般規則,其中上述方法是比較簡單的情況下最好?
當你只需要一些方法,我朝成分往往與委託。 –
爲什麼你不能使用哈希?出了什麼問題?當您想要添加或更改方法時使用子類化,而不是在您想要刪除它們時使用。 – sawa
@sawa,也許我不清楚。我確實想添加或更改方法。我的例子添加了「reindex」方法。 –