Earlier quoted context omitted.
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 hi…
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.
[].slice(5, 100)
^-- *THIS* either returns nil or throws an exception.Edit: Longer example:
puts "[1, 2, 3].slice(1, 100) -> #{[1, 2, 3].slice(1, 100).to_s}"
puts "[1, 2, 3].slice(3, 100) -> #{[1, 2, 3].slice(3, 100).to_s}"
puts "[1, 2, 3].slice(4, 100) -> #{[1, 2, 3].slice(4, 100).to_s}"
Yields: [1, 2, 3].slice(1, 100) -> [2, 3]
[1, 2, 3].slice(3, 100) -> []
[1, 2, 3].slice(4, 100) ->
So, there is a behavior difference between "array a little too short" and "array slightly more too short" that creates unexpected behavior.That's not a big surprise in a tiny example like this; but if you expand this out into a larger code base, where you're just being an array and you want the 100 through 110th values for whatever reason - say it's a csv. Suddenly you're having to consider both the nil case and the empty array case; but then why are they different?