2009-11-10 46 views
0

這是將'each'調用轉發給Hash的本地方法的最有效方法。代理Ruby中的每種方法

我應該讓@index在外面可見嗎?

我有點不確定,因爲塊是invovled。

class TimeSlice 
    def initialize(list) 
    # @index is a hash 
    @index = list.do_some_magic() 
    end 

    def each(&block) 
    @index.each(&block) 
    end 
end 
+0

謝謝你們! – reto 2009-11-10 09:48:40

回答

2

@index應該是私密的。不需要將其暴露在類範圍之外。 如果您只需要委託each方法,則您的示例非常好。

對於更復雜的情況,您可以考慮實施代表設計模式。 Ruby配有Delegate module

1

當談到效率,我不認爲它有什麼問題。但是,你應該保持@index的私密性,否則包裝的整個點each方法丟失。