Check if an array index exist

Hi guys, I am actually coding a parser, and in my program I need to check if an index exist or not in the array. I did this, but when I try to run the code, crystal raise an error that my condition have an index out of bound, why ?

elsif Parser::ElseFilter.matches?(strippedLine)
    if !elsePresence[currentIfLevel-1].nil? && elsePresence[currentIfLevel-1] || elsePresence[currentIfLevel-1].nil?
        puts elsePresence.inspect
        puts currentIfLevel-1
        raise("Line #{index+1}\nFile: #{path}\nExtra else: #{line}\nAn extra \"else\" was declared.")
    end

Normally because I check if it is nil, I should not have problem with my condition no ?

Use #[]? instead of #[] which will return nil instead of raising an exception

If you want to check if and index exists, you could use index < arr.size

Or 0 <= index < arr.size if you want to be completely sure :grin: