Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Some #[]?(Range) methods can still raise IndexError #14340

Closed
HertzDevil opened this issue Mar 3, 2024 · 0 comments · Fixed by #14444
Closed

Some #[]?(Range) methods can still raise IndexError #14340

HertzDevil opened this issue Mar 3, 2024 · 0 comments · Fixed by #14444

Comments

@HertzDevil
Copy link
Contributor

HertzDevil commented Mar 3, 2024

There are 4 types in the standard library that define both #[]?(range : Range) and #[]?(start : Int, count : Int). When the start index is too small, the latter always returns nil, but the first may still raise IndexError nonetheless:

def foo(x)
  a = begin; x[-3, 2]?; rescue ex; ex; end
  b = begin; x[-3..-2]?; rescue ex; ex; end
  c = begin; x[3, 2]?; rescue ex; ex; end
  d = begin; x[3..4]?; rescue ex; ex; end

  {a, b, c, d}
end

foo([0, 0])             # => {nil, nil, nil, nil}
foo(Slice[0, 0])        # => {nil, #<IndexError:Index out of bounds>, nil, nil}
foo("00")               # => {nil, nil, nil, nil}
foo("00".match!(/(.)/)) # => {nil, #<IndexError:Index out of bounds>, nil, nil}

This does not seem to be intended behavior; all kinds of out-of-range calls to #[]? should return nil, not just ones whose range start index is large enough.

(This does not concern with the definition of "out-of-bound" itself, which is currently different for Slice; what matters here is that #[] and #[]? agree on their notions of "out-of-bound".)

(The internal StringScanner::StringMatchData defines only the Range overload. It never raises IndexError.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant