Hello
The problem is caused by negative indices:
a=[1,2,3]
a[-3..-1] does work # ==a
a[-4..-1] # -> nil # should be [1,2,3] # -> this could be
considered as Ruby-Bug
Does someone want to make a bugreport?
I'm not sure if this is a bug. As documented at
"When a single Range argument range is given, treats range.min as start
above and range.size as length above"
Given your example:
(-4..-1).min # -> -4
(-4..-1).size # -> 4
# Same as a[-4..-1]
a[-4, 4] # -> nil
I can't find a discussion in the documentation what should happen in the
specific case where the start argument is outside the range of the array;
however, there is a discussion about the case where the index argument for
the single argument form of the method call is out of range:
"If index is negative, counts relative to the end of self... If index is
out of range, returns nil."
It seems that the implementation of #[start, length] short circuits in your
case because start is out of range for the array. The length argument is
ignored and nil is returned. If there is a bug here, I think it's a
documentation bug that could be corrected by discussing this particular
case.
Moreover I think [nil,1,2,3] is more correct than [1,2,3]. - Which one
is better?
Personally, I think raising RangeError is better. When I'm slicing arrays,
using either a Range or start and length arguments, I expect to get an
array out. I don't expect to get nil. I don't want to do like golang and
litter my code with conditionals looking for nil in case I mess up indexing
into the array. I would prefer to get an exception right at the point the
mistake is made rather than get a mysterious "NoMethodError for
nil:NilClass" somewhere down the line. I think this should also happen for
the "index out of range case" too for much the same reason, namely that I
probably don't expect to get a nil out of my array and would prefer to know
I actually attempted to index outside the range of the array instead of
tracking down where an unexpected nil came from later in the code.
In any case, I think returning either of the array outputs you suggest is
similarly confusing and a potential source of hard to diagnose bugs in
downstream code. Ruby would help me much more as a developer by telling me
that I'm using an array in a nonsensical way than trying to hide that from
me by giving surprising values, even if documentation fully covers those
cases.
-Jeremy
···
On Thu, Aug 11, 2022 at 9:55 AM Die Optimisten <inform@die-optimisten.net> wrote: