Possible Duplicate:
Array slicing in Ruby: looking for explanation for illogical behaviour (taken from Rubykoans.com)
I've been playing around with array slicing in ruby but I don't understand the last 2 results below:
a = [1,2,3]
a[2,1] # output is [3]
a[3,1] # output is [] ...why??
a[4,1] # output is nil ...according to the docs this makes sense
Why would a[3,1]
be an empty array while a[4,1]
is nil?
If anything, I would expect a[3,1]
to return nil as well. According to the ruby docs an ar开发者_StackOverflowray split should return nil if the start index is out of range. So why is it that a[3,1]
is not returning nil?
Note: This is on ruby 1.9.2
You're asking for the end of the array, which is []
. Look at it this way: the Array [1,2,3]
can be considered to be constructed from cons cells as such: (1, (2, (3, ()))
, or 1:2:3:[]
. The 3rd index (4th item) is then clearly []
.
" Returns nil if the index (or starting index) are out of range."
a[3,1]
is a special case according to the example in the same link.
more info can be seen here by the way: Array slicing in Ruby: looking for explanation for illogical behaviour (taken from Rubykoans.com)
It's easier to understand why if you imagine the slice on the left side of an assignment.
>> (b = a.clone)[2,1] = :a; p b
[1, 2, :a]
>> (b = a.clone)[2,0] = :b; p b
[1, 2, :b, 3]
>> (b = a.clone)[3,1] = :c; p b
[1, 2, 3, :c]
>> (b = a.clone)[3,0] = :d; p b
[1, 2, 3, :d]
精彩评论