Possible Duplicate:
Array slicing in Ruby: looking for explanation for illogical behaviour (taken from Rubykoans.com)
Say you have an array
a = [1,2,3]
why the a.slice(3,6)
returns []
while the a.slice(4,6)
returns nil
?
Possible Duplicate:
Array slicing in Ruby: looking for explanation for illogical behaviour (taken from Rubykoans.com)
Say you have an array
a = [1,2,3]
why the a.slice(3,6)
returns []
while the a.slice(4,6)
returns nil
?
The documentation lists special cases for when the start index equal to the length of the array:
a = [ "a", "b", "c", "d", "e" ]
# special cases
a[5, 1] #=> []
a[5..10] #=> []
from: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-slice
So this appears to be the built-in functionality, since the start index is the length of the array the slice method is supposed to return an []
, but when you pass the length of the array you get nil
. This is probably due to how Ruby is defining ranges within an array.
The mechanism is designed this way so slices can work in a highly generalized way on the left-hand side of assignment operators.
It doesn't really matter for #slice
exactly because that result cannot be assigned but the same interpretation applies to x[3, 6]
and those expressions can be assigned.
It's best to look at the array indices as identifying the spaces between elements, rather than the elements themselves.
This interpretation creates a consistent and useful interface ... for example, code can be written that will handle replacing elements or appending to zero length or populated Arrays, and all without needing special-case tests.