Array#insert implementation

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?

"Zuzzurro" <celhoquilabrioche@zuzzurro.it> 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

Zuzzurro wrote:

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]

thank you.

···

Il giorno mar, 25-01-2005 alle 16:32 +0100, Robert Klemme ha scritto:

"Zuzzurro" <celhoquilabrioche@zuzzurro.it> 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

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.

···

Il giorno mar, 25-01-2005 alle 22:23 +0100, Florian Gross ha scritto:

Zuzzurro wrote:

> 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]