Array#[] and Out of Range

Hello.

I’m a bit puzzled by Array#[]'s behaviour. The documentation says
“Returns nil if the index (or starting index) are out of range.” which
doesn’t explain the following for me:

(x is an arbitrary integer)

[:x][1…x] => []

Isn’t index 1 out of range for an array with one element?

[][0…x] => []

Isn’t index 0 out of range for an empty array?

I could write more examples, but I hope they illustrate my point.

Thanks,

It makes sense. Your subscripts are ranges of indices, not indices. Ruby
gives you the subarray specified by the indices in the range. In both of
your examples, you get empty arrays. Were you expecting to get arrays of
nils?

Hello.

It makes sense. Your subscripts are ranges of indices, not indices. Ruby
gives you the subarray specified by the indices in the range. In both of
your examples, you get empty arrays. Were you expecting to get arrays of
nils?

I realize I should have added another example:

[:x][2…x] => nil

The return values of the two previous examples are actually what I’d
expected, but it doesn’t seem to with consistent with my latest
example or the documentation. As I read it, in the case of ranges
“starting index” refers to Range#first.

Thanks,

Christoffer S. wrote:

The return values of the two previous examples are actually what I’d
expected, but it doesn’t seem to with consistent with my latest
example or the documentation. As I read it, in the case of ranges
“starting index” refers to Range#first.

Further down in the documentation you’re referring to:
a = [ “a”, “b”, “c”, “d”, “e” ]

a[4…7] #=> [ “e” ]
a[6…10] #=> nil

a[5] #=> nil
a[5, 1] #=> []
a[5…10] #=> []

This makes sense because a[5…5] needs to return [] for symmetry with
a[0…0].

Cheers,
Dave