Array#insert implementation

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?
 
R

Robert Klemme

Zuzzurro said:
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
 
Z

Zuzzurro

Il giorno mar, 25-01-2005 alle 16:32 +0100, Robert Klemme ha scritto:
Zuzzurro said:
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

thank you.
 
F

Florian Gross

Zuzzurro said:
class Array
def insert(v, i)
[...]
Is there a better way of doing this?

Sure, just use Array#insert:

irb(main):043:0> ary = [1, 2, 3]; ary.insert(1, 5); ary
=> [1, 5, 2, 3]
 
Z

Zuzzurro

Il giorno mar, 25-01-2005 alle 22:23 +0100, Florian Gross ha scritto:
Zuzzurro said:
class Array
def insert(v, i)
[...]
Is there a better way of doing this?

Sure, just use Array#insert:

irb(main):043:0> ary = [1, 2, 3]; ary.insert(1, 5); ary
=> [1, 5, 2, 3]

nice to see they added #insert in the 1.8 version, I'm still using 1.6
tough, so I did the following:

class Array
def insert(i, v)
self[i,0] = v
end
end

as suggested by Robert Klemme.

Regards,
Paolo.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,166
Messages
2,570,901
Members
47,442
Latest member
KevinLocki

Latest Threads

Top