How does .insert work?

Viewed 27039

I'm trying to figure out what the insert function does in Ruby.

I've consulted Google and ruby-doc.com but the explanation is not sufficient to describe this (seemingly) mysterious function.

Here's what's confusing me:

a = %w{a b c d}
puts a.insert(4, 5)  output = a,b,c,d,5

The first question raised is, why is the 4 not inserted?

puts a.insert(2,2,6)

The output is:

a
b
2
6
c
d

Two questions raised by this are

  1. Why is 2 not inserted twice?
  2. Why are 2 and six (seemingly) arbitrarily placed between b and c?
2 Answers
Related