From: Rob Biedenharn Date: 2010-09-13T12:22:58+09:00 Subject: Re: array[index,length] strange behaviour On Sep 12, 2010, at 10:55 PM, Mikel Lindsaar wrote: > Hi all, > > Running Ruby 1.8.7. And I saw Jim Weirich's post about the Ruby > Koans, and I thought, what the hey! Lets do them! > > So I downloaded, and what do you know! I found something I didn't > understand!! :) > > Anyway, per http://ruby-doc.org/core/classes/Array.html#M002205 it > says: "Returns nil if the index (or starting index) are out of > range". > > So given array: > > array = [:peanut, :butter, :and, :jelly] > > One would expect: > > array[4] == nil #=> true > array[5] == nil #=> true > > Which works, 4 and 5 are both out of range. > > However: > > array[4,0] == nil #=> false > array[5,0] == nil #=> true > > Huh? In actual fact array[4,0] returns an empty array. This seems > in conflict with the docs. > > Can someone more enlightened please explain? > > Thank you! > > Mikel Well, the docs seem to describe the behavior properly. You have to read them closely when it says "equal to the array size..." but Programming Ruby (1.8 and 1.9) have essentially the same text. Here's a way I've thought about it: Picture the array with the comma after each element: [ :peanut, :butter, :and, :jelly, ] Then the first index is how many commas to skip before starting. So 4 puts your mental cursor after the :jelly, but before the ] [ :peanut, :butter, :and, :jelly, ] ^ Then you're still "in" the array and take as many elements as possible. Since there aren't any more, array[4,0] == array[4,1000] == [] When trying to find the starting point for array[5,n], there's no 5th comma before the ] that ends the array. So you get nil. It helps me so I hope this description helps you, too! -Rob Rob Biedenharn Rob@AgileConsultingLLC.com http://AgileConsultingLLC.com/ rab@GaslightSoftware.com http://GaslightSoftware.com/