From: Joel VanderWerf Date: 2004-04-19T06:36:56+09:00 Subject: Re: 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.