From: Marko Schulz Date: 2001-04-28T19:35:25+09:00 Subject: [ruby-talk:14371] Re: RCR: Array#insert On Sat, Apr 28, 2001 at 12:00:58PM +0900, TAKAHASHI Masayoshi wrote: > > Another candidate is: > > [ Another possible implementation of Array#insert ] I would actually prefer an version that is able to insert more than one element, just like push can add more than one element at the end. So here is my take: class Array def insert(pos, *elem) self[pos,0] = elem self end end a=[1,2,3,4,5,6] ==>[1, 2, 3, 4, 5, 6] a.insert(2,"new") ==>[1, 2, "new", 3, 4, 5, 6] a.insert(5,"two","entries") ==>[1, 2, "new", 3, 4, "two", "entries", 5, 6] a.insert(0, "At","the","start") # Similar to unshift, but with more elements ==>["At", "the", "start", 1, 2, "new", 3, 4, "two", "entries", 5, 6] I also pondered about a variant that handles negativ indeces a bit different: -1 inserts after the last element, -2 before the last, -3 before the last but one ...: class Array def insert(pos, *elem) if pos == -1 pos = self.length elsif pos < 0 pos += 1 end self[pos,0] = elem self end end a=[1,2,3,4,5,6] ==>[1, 2, 3, 4, 5, 6] a.insert(-1,"end") # Similar to push ==>[1, 2, 3, 4, 5, 6, "end"] a.insert(-2,*%w(just before the)) ==>[1, 2, 3, 4, 5, 6, "just", "before", "the", "end"] -- marko schulz Dieser Satz beinhalten drei Fehller.