Skip to content

Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

Array#insert

array.insert(index, *objects) → self

Inserts given objects before or after the element at Integer index offset; returns self.

When index is non-negative, inserts all given objects before the element at offset index:

Example
a = [:foo, 'bar', 2]
a.insert(1, :bat, :bam) # => [:foo, :bat, :bam, "bar", 2]

Extends the array if index is beyond the array (index >= self.size):

Example
a = [:foo, 'bar', 2]
a.insert(5, :bat, :bam)
a # => [:foo, "bar", 2, nil, nil, :bat, :bam]

Does nothing if no objects given:

Example
a = [:foo, 'bar', 2]
a.insert(1)
a.insert(50)
a.insert(-50)
a # => [:foo, "bar", 2]

When index is negative, inserts all given objects after the element at offset index+self.size:

Example
a = [:foo, 'bar', 2]
a.insert(-2, :bat, :bam)
a # => [:foo, "bar", :bat, :bam, 2]
See also #initialize_copy #inspect #index #intersect? also in 4.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0