Z
Zuzzurro
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?
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?