How do I insert into an array?

Sam Roberts wrote:

I want to add an item just before the end:

rb(main):003:0> a = [1,2,3]
[1, 2, 3]
irb(main):004:0> last=a.pop; a.push “second last”; a.push last
[1, 2, “second last”, 3]

Is there a better way than this “pop,push,push” thing? I looked for an
Array.insert, but can’t find anything like it.

Here’s a way:

irb(main):001:0> a = [1,2,3]
=> [1, 2, 3]
irb(main):002:0> a[-1,0] = “second last”
=> “second last”
irb(main):003:0> a
=> [1, 2, “second last”, 3]

The -1 in a[-1,0] is obtained by counting backwards from the end of the
array. The 0 is the size of the “selection” you want to “replace”, so 0
just means insert.

Another way is to use ranges:

irb(main):009:0> a = [1,2,3]
=> [1, 2, 3]
irb(main):010:0> a[2…2] = “second last”
=> “second last”
irb(main):011:0> a
=> [1, 2, “second last”, 3]

Use the … form instead of the … form, or else a[2] will be replaced.

Joel VanderWerf wrote:

Sam Roberts wrote:

I want to add an item just before the end:

Another way is to use ranges:

irb(main):009:0> a = [1,2,3]
=> [1, 2, 3]
irb(main):010:0> a[2…2] = “second last”

Oops. Unless you want to calculate the length yourself, you’re better
off with:

                a[-1...-1] = "second last"

Quoteing vjoel@PATH.Berkeley.EDU, on Mon, Apr 19, 2004 at 06:36:56AM +0900:

Sam Roberts wrote:

I want to add an item just before the end:

Here’s a way:

irb(main):001:0> a = [1,2,3]
=> [1, 2, 3]
irb(main):002:0> a[-1,0] = “second last”
=> “second last”

That’s great, thanks.

I never read past where it said that kind of call “replaced” things,
because I don’t want to replace things. It never occurred to me I could
'replace" zero things!

Sam