public Method

Array.insert(...)

array.insert(index, obj...)   array

Inserts the given values before the element with the given index (which may be negative).

a = %w{ a b c d }
a.insert(2, 99)         #=> ["a", "b", 99, "c", "d"]
a.insert(-2, 1, 2, 3)   #=> ["a", "b", 99, "c", 1, 2, 3, "d"]

Source Code

/*
*  call-seq:
*     array.insert(index, obj...)  -> array
*  
*  Inserts the given values before the element with the given index
*  (which may be negative).
*     
*     a = %w{ a b c d }
*     a.insert(2, 99)         #=> ["a", "b", 99, "c", "d"]
*     a.insert(-2, 1, 2, 3)   #=> ["a", "b", 99, "c", 1, 2, 3, "d"]
*/

static VALUE
rb_ary_insert(argc, argv, ary)
   int argc;
   VALUE *argv;
   VALUE ary;
{
   long pos;

   if (argc == 1) return ary;
   if (argc < 1) {
       rb_raise(rb_eArgError, "wrong number of arguments (at least 1)");
   }
   pos = NUM2LONG(argv[0]);
   if (pos == -1) {
       pos = RARRAY(ary)->len;
   }
   if (pos < 0) {
       pos++;
   }
   rb_ary_splice(ary, pos, 0, rb_ary_new4(argc - 1, argv + 1));
   return ary;
}
Comments

Have your say
Please use Textile formatting (click here for a cheat sheet). Use <code/> and <pre/> for code samples.
Click here to login with OpenID to to post comments.