Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
Array#insert
(::int index, *Elem objects) -> self
insert(index, *objects) → self
array.c
View on GitHub ↗
static VALUE
rb_ary_insert(int argc, VALUE *argv, VALUE ary)
{
rb_len_t pos;
rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
rb_ary_modify_check(ary);
pos = NUM2LEN(argv[0]);
if (argc == 1) return ary;
if (pos == -1) {
pos = RARRAY_LEN(ary);
}
else if (pos < 0) {
rb_len_t minpos = -RARRAY_LEN(ary) - 1;
if (pos < minpos) {
rb_raise(rb_eIndexError, "index %"PRIdLEN" too small for array; minimum: %"PRIdLEN,
pos, minpos);
}
pos++;
}
ary_splice(ary, pos, 0, argv + 1, argc - 1, FALSE);
return ary;
}
Inserts the given objects as elements of self; returns self.
When index is non-negative, inserts objects before the element at offset index:
Example
a = ['a', 'b', 'c'] # => ["a", "b", "c"] a.insert(1, :x, :y, :z) # => ["a", :x, :y, :z, "b", "c"]
Extends the array if index is beyond the array (index >= self.size):
Example
a = ['a', 'b', 'c'] # => ["a", "b", "c"] a.insert(5, :x, :y, :z) # => ["a", "b", "c", nil, nil, :x, :y, :z]
When index is negative, inserts objects after the element at offset index + self.size:
Example
a = ['a', 'b', 'c'] # => ["a", "b", "c"] a.insert(-2, :x, :y, :z) # => ["a", "b", :x, :y, :z, "c"]
With no objects given, does nothing:
Example
a = ['a', 'b', 'c'] # => ["a", "b", "c"] a.insert(1) # => ["a", "b", "c"] a.insert(50) # => ["a", "b", "c"] a.insert(-50) # => ["a", "b", "c"]
Raises IndexError if objects are given and index is negative and out of range.
Related: see Methods for Assigning.