Thanks for the quick reply.

I ran some tests in ruby:

array = [1,2,3,4]
p array.insert(-3, 'one', 'two')
array = [1,2,3,4]
p array.insert(-1, 'one', 'two')
array = [1,2,3,4]
p array.insert(0, 'one', 'two')
array = [1,2,3,4]
p array.insert(1, 'one', 'two')
array = [1,2,3,4]
p array.insert(10, 'one', 'two')

output:
[1, 2, "one", "two", 3, 4]
[1, 2, 3, 4, "one", "two"]
["one", "two", 1, 2, 3, 4]
[1, "one", "two", 2, 3, 4]
[1, 2, 3, 4, nil, nil, nil, nil, nil, nil, "one", "two"]

when the index is negative and of greater length than the array, ruby
throws an index out of bounds exception.

On Mar 27, 4:06 pm, Ken Snyder <[EMAIL PROTECTED]> wrote:
> koozdra wrote:
> > I propose the addition of Array.insert(index, insertee [,...]).  This
> > method would would be like Ruby's insert. "Inserts the given values
> > before the element with the given index"
> > -http://www.ruby-doc.org/core/classes/Array.html#M002195
>
> > var a = ['a','b','c','d']
>
> > a.insert(2, 33)
> > --> ['a','b',33,'c','d']
>
> > a.insert(3, 'one', 'two', 'three')
> > -->['a','b','c','one', 'two', 'three','d']
>
> > --
> > Dimitri
>
> I always have mixed feelings about wrappers for Array#splice.  It is a
> very powerful method that needs no knock off, yet it is very hard to
> remember.  Anyhow, below is an academic stab at implementing your idea.
> My only question is what to do when the index is too low or too high.
> I'm not sure what Ruby does; the code below just defaults to 0 when the
> index is too low or too high.
>
> - Ken Snyder
>
> Array.prototype.insert = function() {
>     var args = $A(arguments), index = args.shift();
>     index = index < 0 ? this[this.length - index] : index;
>     args = [(this[index] === undefined ? 0 : index), 0].concat(args);
>     Array.prototype.splice.apply(this, args);
>
> }
>
> var a = ['a','b','c','d'];
> a.insert(2, 33);
> console.log(a);
> // ["a", "b", 33, "c", "d"]
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Prototype: Core" group.
To post to this group, send email to prototype-core@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/prototype-core?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to