logoalt Hacker News

weaksauceyesterday at 12:38 AM1 replyview on HN

the docs say... if index is out of range return nil. the edge case is that if you specify the exact end index of the array and want a slice of that index to 100 it will return an empty array. if you go out of bounds it informs you that you are out of bounds with nil. not sure it's the best api but probably is mimicking some C api somewhere as a lot of ruby does that. that said it will never error on this alone but it will almost certainly error if you chain it with something not expecting nil.

The easiest way to get around that if you are not carefully using the ranges would be to do `Array(array.slice(a, b))` as that will guarantee an array even if it's invalid. you could override slice if you really wanted to but that would be a performance penalty if you are doing it often.


Replies

t-writescodeyesterday at 1:20 AM

Indeed. I had heard that it was a carryover from C; but for an "implicit is better than explicit" and "magic ducktyping, it just works, I promise" language, like Ruby, this feels like a direct contradiction to its intended behavior and this specific example has always stood out to me in a "... but why?" sort of way.

show 1 reply