Array slicing in Ruby: explanation for illogical behaviour (taken from Rubykoans.com)

Slicing and indexing are two different operations, and inferring the behaviour of one from the other is where your problem lies.

The first argument in slice identifies not the element but the places between elements, defining spans (and not elements themselves):

  :peanut   :butter   :and   :jelly
0         1         2      3        4

4 is still within the array, just barely; if you request 0 elements, you get the empty end of the array. But there is no index 5, so you can’t slice from there.

When you do index (like array[4]), you are pointing at elements themselves, so the indices only go from 0 to 3.

Leave a Comment