Issue #16822 has been updated by marcandre (Marc-Andre Lafortune).


I'm strongly against this, for compatibility reasons and because current choice is a consistent convention.

Before proposing any incompatible change, especially for an API that is very much in use, please provide a compelling use case. If you write `ary[1..].reduce { }`, you must give a context (what contains `ary`, why would you want to skip the first value, why not use `values_at(1..)`, etc.).

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

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

I propose that methods that slice an array (`#slice` and `#[]`) and return a sub-array in the normal case, should **never** return `nil`. E.g.,

```ruby
ary = [1, 2, 3]
```

* 1. Non-empty slice--how it works currently

```ruby
a[1..2] # => [2, 3]
a[1...-1] # => [2]
```

* 2. Empty slice--how it works currently

```ruby
a[1...1] # => []
a[3...] # => []
a[-1..-2] # => [] 
```

* 3. Sudden `nil`**what I am proposing to change**

```ruby
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 the array at the requested address, you'll have an empty array).

Most of the time, the empty array doesn't require any special handling; thus, `ary[start...end].map { ... }` will behave as expected if the requested range is outside of the array boundary.

It is especially painful with off-by-one errors; for an array of three elements, if `ary[3...]` (just outside the boundary) is `[]` while `a[4...]` (one more step outside) is `nil`, it typically results in some nasty `NoMethodError for NilClass`.

A similar example is `ary[1..].reduce { }` (everything except the first element--probably the first element was used to construct the initial value for reducing) with `ary` being non-empty 99.9% of the times. Then you meet one of the 0.1% cases, 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>