tags:

views:

83

answers:

3

I am writing an method that takes variable lengths of arrays and compresses and converts them to matching array lengths.

The method accepts an array length of anywhere from 50 to 126 . .. and converts them down based on parameters when called. This means is I am dynamically accessing ranges that are specified at method call. This also means I will be accessing indices of the array that won't exist. In addition to this, the range I am accessing may be equal. This is where my problem lies: it appears that the terminating pocket of an array behaves strangely when accessing it with a range, as opposed to any other non-existent index

>> a = [0, 1, 2, 3, 4]
# => [0, 1, 2, 3, 4]  

>> a[5]
# => nil  

>> a[4..4]
# => [4]

>> a[6..6]
# => nil  

>> a[5..5]
# => [] <------GGRAAAAAhhh!!! Thought you were nil

>> a[5..7]
# => []   <-------you too

>> a[6..7]
# => nil <-----but you are behaving

Does anyone know why this happens? Its an extra test against an empty array for my code, but I am more curious after chasing this bug down in my rails app all day. FWIW I am running Ruby 1.8.6 on Mac OS X, patchlevel 114

+3  A: 

Seems strange but it's a documented behaviour: http://www.ruby-doc.org/core/classes/Array.html#M002183

Jonas Elfström
+2  A: 

The out-of range range selection is a special case, and works as per the docs:

http://www.ruby-doc.org/core/classes/Array.html#M002183

Though I'd agree that it's not exactly obvious.

Mr. Matt
Mr Matt won by a minute, but I voted both answer up. Thanks guys
BushyMark
A: 
zenazn
Yes you can but I still think you are on to something here because if a[3..3] returned nil in your case, you wouldn't be able to add to the end of an array in that way. If adding to the end, and not to any position including the end, I would prefer a=a+[4,5] or a<<4<<5 though.
Jonas Elfström