Newby Slicing Question

Okay, I’ve seen this question about the d*mn ruby koans posted several
places, but one aspect of fencepost slicing still eludes me.
In the following array:
array = [:peanut, :butter, :and, :jelly]

I get:
assert_equal [], array[4,0]

The “fence post” at the end of the array after :jelly exists and doesn’t
give a nil.

I don’t get why:
assert_equal [:jelly], array[4,-1]

Any pointers to clear this up?
Thanks and sorry if this has been asked 1000.times, I really did search!

array[4,0]
returns an array containing 0 elements, starting at the fourth, ie an
empty array, which is equal to [].

array[4,-1]
returns nil, and [:jelly] is not equal to nil.

See the ruby docs:

ary[start, length] → new_ary or nil
Returns nil if the index (or starting index) are out of range.

array = [:peanut, :butter, :and, :jelly]
array[4,0] # => []
array[4,-1] # => nil
array[4…-1] # => []

array[3…-1] # => [:jelly]
array[3…3] # => [:jelly]

array[1…-3] # => [:butter]
array[1…1] # => [:butter]

Hi,

ary[start, length] → new_ary or nil
  1. A negative length returns nil:

    array = %i[peanut butter banana jelly]
    p array[2, -1] #=>nil

  2. A length of 0 can return a new array or nil:

    p array[100, 0] #=> nil
    p array[4, 0] #=>[]

To understand the last result, read the best post ever written on
slicing(although it is written for strings):

https://www.ruby-forum.com/topic/1393096#990065

My interpretation is that the index 4 is legal in two arg indexing,
and the length 0 is a legal length(i.e. it’s not negative), and
adding 0 to 4 does not go out of bounds, so nil is not the proper
return value.

But really, ruby could have been coded to return nil when you take a
slice of 0 length at the ending fencepost. You just have to accept:
That’s the way it is.