Remix.run Logo
bradchris 3 hours ago

Because [] is an array with nothing in it, and [0] is an array with something in it.

So saying “give me the array containing the first 100 elements of this array with one element” would obviously give you the array with one element back.

Saying “give me the array containing the first 100 elements of this array with zero elements” would follow that it just gives the empty array back.

On top of that, because ruby is historically duck-typed, having something always return an array or an error makes sense, why return nil when there’s a logical explanation for defined behavior? Ditto for throwing an error.

Seems thoughtfully intuitive to me.

saghm 2 hours ago | parent [-]

Yeah, returning an empty array is pretty much exactly what I would expect given the first example. It would be a lot weirder to me if you were allowed to give an end index past the last element only if the array happened to be non-empty.

bradchris 2 hours ago | parent [-]

Especially because in ruby

[0, nil, nil, nil, …x100, nil] is the same as [0] in terms of access.

In both cases, trying to access the 100th element (e.g. [0][100]) will give nil.