From: Robert Klemme Date: 2005-01-26T00:35:55+09:00 Subject: Re: Array#insert implementation "Zuzzurro" schrieb im Newsbeitrag news:1106665910.3709.5.camel@localhost.localdomain... > Hi, > > I need an insert method for the Array class, the insert method let you > do something like this: > > a = ['a', 'b', 'd'] > a.insert!(2, 'C') > > a => ['a', 'b', 'C', 'd'] > > > I've implemented it this way: > > class Array > def insert(v, i) > i = 0 if i < 0 > a = Array.new > a += self[0..i-1] if i > 0 > a << v > tail = self[i..-1] if i < self.length > a += tail unless tail.nil? > return a > end > > def insert!(v, i) > new_self = insert(v, i) > clear > concat new_self > end > end > > > Is there a better way of doing this? >> a = %w{a b c d} => ["a", "b", "c", "d"] >> a[2,0]=%w{1 2 3} => ["1", "2", "3"] >> a => ["a", "b", "1", "2", "3", "c", "d"] Kind regards robert