From: Ian Hobson Date: 2009-04-05T04:58:04+09:00 Subject: Re: Array#insert with negative index Christopher Dicely wrote: > On Fri, Apr 3, 2009 at 12:49 PM, matt neuburg wrote: > >> p [1,2,3].insert(-1, "howdy") >> #=> [1, 2, 3, "howdy"] >> >> Docs: "Inserts the given values before the element with the given index >> (which may be negative)." >> > > Clearly, a more accurate statement of the existing behavior would be > "Inserts the given values such that the first value (last if the index > given is negative) will have the given index." > > This is wrong. (and therefore confusing). I suspect that what you were trying to say was "The value is inserted so it becomes the element at the index given". (which is accurate unless an error occurs). irb(main):006:0> a = [1,2,3] => [1, 2, 3] irb(main):007:0> a[2] => 3 irb(main):008:0> a[-2] => 2 irb(main):009:0> a.insert(-2,"x") => [1, 2, "x", 3] irb(main):010:0> [1,2,3].insert(2,"y") => [1, 2, "y", 3] irb(main):011:0> For the manual..... (Version 1.8.6) " insert(pos, val) will insert object val such that it becomes the element at position pos, pushing any later elements right one place. Another way of thinking of this, is that pos is the gap between elements where the new element will go, with the usual positive and negative indexing. For non-negative indexes, 0 is before the first element and you count up to the right. For negative indexes, -1 is after last element, and you count down to the left. Note = positive indexed may extend the array with nil values. Indexes that are too negative give an "Index error - index out of array" error. " Regards Ian