我在使用索引时发现了一些奇怪的行为。
#Defined in the class's initialize
@my_list = [] of Type
index = @my_list.index { |i| i.value == 2 } # => 0
@my_list[0] # => 2
@my_list[index] # => error
我遇到了以下错误:
没有匹配类型为(Int32 | Nil)的'Array(Type)#[]'重载
不确定为什么索引不起作用,因为索引=0。
编辑:
更多信息。如果我这样做:
if index == nil
#Do something
#error => undefined method '>=' for Nil (compile-time type is (Int32 | Nil))
elsif index >= 0
#Do something else
end
我明白。它可能是nil,但既然我已经检查过它是否为nil,这里就不应该有问题。我认为先前的代码片段也遇到了同样的问题。