I’m learning Ruby and have just gotten into some stuff about arrays and ranges. I’ve run into something about slices that, while it makes sense at first glance, confuses me a bit when I look deeper into it.
IRB says that (2..-1).to_a is an empty array, meaning no values in the range, right?
But if I use that same range in [:a, :b, :c, :d, :e][2..-1], I get back [:c, :d, :e] rather than an empty array.
Now, I’m aware that -1 represents the last element of the array, so it kind of makes sense that what got picked, did. But if the range itself would be empty, how is it selecting anything?
This is a fascinating question. The answer is that it’s not the individual elements of the range that are inspected when slicing the array, but the
firstandlastelements. Specifically:Thus the example works, since it slices the array from the
[2]element to the[-1]element.If you want a consistent way to think about this, consider that
(2..-1).to_aoutputs the integers found between2and-1(of which there are none), but that[2..-1]means from the2index to the-1index.(Source:
array.candrange.cin the Ruby source.)And, the complicated bonus part: to get the meaning you were thinking about, you could use