How Ruby Array#slice works

I’ve been slowly working through the Ruby Koans to sharpen my basic ruby fundamentals and came accross Arrary#slice.

What got me stumped for the first couple of minutes:

array = [:peanut, :butter, :and, :jelly]
assert_equal [], array[4,0]   # = []
assert_equal nil, array[5,0]  # = nil

Initially, I thought both assertions should be nil; however, re-reading the Arrary#slice documentation, I’ve realized I’ve misunderstood how it worked (ri Array#slice for the command line). The response given on Stack Overflow, basically says:

…the first number when you slice does not identify the element, but places between elements, in order to be able to define spans (and not elements themselves)

# [ :peanut, :butter, :and, :jelly ]
#  0        1        2     3      4
array[4,0]

# [ :peanut, :butter, :and, :jelly ]
#                                 4
# At index 4 with 0 lengths, hence array[4,0] = []

In other words, 4 is still within the array-just at the end of the array in the context of slicing. In the case of array[5,0], that’s just out of range thus we get nil.