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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Because it makes assignment more general
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
#sliceexactly because that result cannot be assigned but the same interpretation applies tox[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.