Issue #16822 has been reported by zverok (Victor Shepelev).

----------------------------------------
Feature #16822: Array slicing: nils and edge cases
https://bugs.ruby-lang.org/issues/16822

* Author: zverok (Victor Shepelev)
* Status: Open
* Priority: Normal
----------------------------------------
(In before, I understand that the change proposed can break some code, but I empirically expect it to be not a large amount of.)

I propose that array slicing (`#slice` and `#[]`) in contexts when it returns sub-array, should _never_ return `nil`.
E.g.:
```ruby
ary = [1, 2, 3]
# 1. non-empty slice -- that's how it works currently
a[1..2] # => [2, 3]
a[1...-1] # => [2]
# 2. empty slice -- that's how it works currently
a[1...1] # => []
a[3...] # => []
a[-1..-2] # => [] 
# 3. sudden nil -- that's what I am proposing to change
a[4..] # => nil 
a[-10..-9] # => nil 
```

I believe that it would be better because the method would have cleaner "type definition" (if there is nothing in array by requested address -- you'll have empty array). 
Most of the time, the empty array doesn't require any special handling, so `ary[start...end].map { ... }` will behave expected way if the requested range is outside array bounds.

It is especially painful in a form of off-by-one errors, when for an array of 3, `ary[3...]` (just outside the bounds) is `[]`, while `a[4...]` (one more step outside) is `nil`, typically resulting in some nasty `NoMethodError for NilClass`.

Another similar example (and one that just shot my foot just yesterday) is `ary[1..].reduce { }` (everything except the first element -- probably because the first element was used to construct initial value for reducing), in a context, when 99.9% of times `ary` is non-empty. Then you meet that one 0.1%, and instead of no-op reducing nothing, `NoMethodError` is fired.





-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>