From: "David A. Black" Date: 2009-08-03T06:07:45+09:00 Subject: Re: Inconsistency in Array#[] Hi -- On Mon, 3 Aug 2009, Wojciech Piekutowski wrote: > Disclaimer: I know what docs say, but I'd prefer a different > behaviour. I want to understand why this design decision was made. > > Some code first: > irb(main):001:0> a = [1,2,3,4,5] > => [1, 2, 3, 4, 5] > irb(main):002:0> a[0,10] > => [1, 2, 3, 4, 5] # ad 1 > irb(main):003:0> a[-10,10] > => nil # ad 2 > > 1. Get 10 elements starting from the first element until the end of > the array. If array is smaller than 10 just return everything. This > makes sense, because in the range <0, 10) there are 5 elements that > can be returned. > 2. Get 10 elements starting from the 10th element from the end, up to > the end. I got nil, but looking from -10 to 0 there are 5 elements, in > other words in the range (-10, 0> there are 5 elements, like in case > 1. > > I expected I'd get the same result as in 1 (yes, no additional nils, > just the whole array). I think this isn't really complying with the > principle of the least surprise. I'd be grateful if somebody can > explain me a reasoning behind this behaviour. The way I see it, the process short-circuits as soon as it realizes that you're asking it to start at an out-of-range index. The same happens here: array = [1,2,3] array[5,10] # => nil, because there's no a[5] I would also always expect that if this succeeds: sub = array[x,y] then this is true: sub[0] == array[x] since you've asked for a subarray starting at array[x]. If sub[0] isn't array[x], then the subarray cannot be said to have started at array[x]. David -- David A. Black / Ruby Power and Light, LLC / http://www.rubypal.com Q: What's the best way to get a really solid knowledge of Ruby? A: Come to our Ruby training in Edison, New Jersey, September 14-17! Instructors: David A. Black and Erik Kastner More info and registration: http://rubyurl.com/vmzN