[LRUG] Array.slice question

Tom Stuart tom at therye.org
Wed Sep 7 01:52:09 PDT 2011


On 7 Sep 2011, at 09:45, Tom Stuart wrote:

> On 7 Sep 2011, at 09:29, Michael Pavling wrote:
>> when I call x[3,0] I *expect* it to return
>> nil (as the starting index is out of range), but it returns an empty
>> array:
>>>> x[3,0]
>> => []
> 
> Not really an explanation, but this is just how rb_ary_subseq works[1]. It's noted as a special case in the Array#slice documentation[2].
> 
> Cheers,
> -Tom
> 
> [1] https://github.com/ruby/ruby/blob/trunk/array.c#L952
> [2] http://ruby-doc.org/core/classes/Array.html#M000267

Indeed - it looks to me like an off-by-one error which has become institutionalized. The check is for the start value being greater than the length rather than greater-than-or-equal-to, and so an empty array gets returned (line 959).

The special case listed in the docs is actually even more interesting, since the length value in that case is 1. In this case, the test '(RARRAY_LEN(ary) < len || RARRAY_LEN(ary) < beg + len)' passes, and the length gets adjusted to 'length of array - start value', i.e. 0. (line 956) I'm struggling to see why that logic is there - it can't be there just to support the call x[n, 1] where n == x.size, can it?

Cheers,

Other Tom




More information about the Chat mailing list