2011-10-05 23 views
2

我有一個數組date_array。如果i0,我想date_array[i-1]返回nil或例外。我以爲我可以爲此派生一個Array的子​​類,但我不確定在那之後要去哪裏。有任何想法嗎?需要禁止數組中的負指數值

回答

3

你可以做到這一點,但你不應該需要。我覺得你錯了,因爲責任是你的,而不是Array的,來檢查被傳遞的索引值。

僅僅是一個例子

def get_array_value (i) 
    return data_array[i - 1] unless i < 0 
    return nil 
end 

但是,如果你堅持,該解決方案可以爲你工作。

# arr = SpecialArray.new([1, 2, 3, 4, 5]) 

class SpecialArray < Array 

    def [](i) 
    return super(i) unless i < 0 
    return nil 
    end 

end 
+0

是的,改變直接調用數組通過[]到一個函數(就像你上面)一樣正常工作。謝謝。 – davej

0

好吧,我同意亞當,這將會是理想的控制指標,而不是這樣做:

class Ary < Array 
    def [](i) 
     return nil if i < 0 
     super 
    end 
end 

a = Ary.new([1, 2, 3]) 
b = Array.new([1, 2, 3]) 

#try access with -1 (normally would show last) 
p a[-1] #=> nil 
p b[-1] #=> 3 
0

我想你可能被錯誤地做事情。這就是說:

你可以使用散列而不是數組。哈希不會重新解釋hash[-1]意思是別的。

0

您可以重寫默認數組的行爲。請注意,當索引超出限制時,Array #fetch方法會引發異常。您可以將該方法包裝在#[]中。這裏是一個例子

class Array 
    def [](index) 
    self.fetch(index) 
    end 
end 

現在,它應該只是工作。額外的好處是,你不需要實施任何新的東西。只需使用現有的標準實現即可。