Forum: Ruby Array#[] and Out of Range

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Christoffer S. (Guest)
on 2006-05-21 23:34
(Received via mailing list)
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,
Francis C. (Guest)
on 2006-05-21 23:52
(Received via mailing list)
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?
Christoffer S. (Guest)
on 2006-05-22 00:14
(Received via mailing list)
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,
Dave B. (Guest)
on 2006-05-22 12:42
(Received via mailing list)
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
This topic is locked and can not be replied to.