2011-10-10 17 views
1

在一個Array子類(只是一個數組,可以強制輸入值)我定義了#concat以確保值被強制。由於沒有人使用#concat並更可能使用#+=我試圖將別名#+=改爲#concat,但它似乎永遠不會被調用。有任何想法嗎?試圖在數組子類中重新定義+ =似乎沒有做任何事情?

請注意,強制實際上總是通過特定超類的對象(它通過構造函數接受輸入),以防此代碼看起來不符合我所描述的內容。它是內部私有API的一部分。

class CoercedArray < Array 
    def initialize(type) 
     super() 
     @type = type 
    end 

    def push(object) 
     object = @type.new(object) unless object.kind_of?(@type) 
     super 
    end 

    def <<(object) 
     push(object) 
    end 

    def concat(other) 
     raise ArgumentError, "Cannot append #{other.class} to #{self.class}<#{@type}>" unless other.kind_of?(Array) 
     super(other.inject(CoercedArray.new(@type)) { |ary, v| ary.push(v) }) 
    end 

    alias :"+=" :concat 
    end 

#concat工作正常,但#+=似乎是完全繞過。

回答

5

由於a += b是句法糖a = a + b我試圖覆蓋+方法。

+0

我不知道,謝謝!現在工作:) – d11wtq

相關問題