我有一个数组date_array
。如果i
是0
,我希望date_array[i-1]
返回nil
或异常。我认为我可以派生一个子类来实现这个,但我不确定接下来该怎么做。有什么想法吗?
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
嗯,我同意Adam的观点,最好控制索引而不是这样做:
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
我认为你可能在做事情时有些不正确。话虽如此:
你可以使用哈希表而不是数组。哈希表不会重新解释 hash[-1]
为其他含义。