What is the insert method in Ruby?

The insert method in Ruby is used to insert an element to a given string or an array. The insert method takes in two parameters: an index and the element. The first parameter is the index, whereas the second is the element. The insert method then returns the modified string or array.

The insert method places the element at the index specified in the parameter.

Indexing begins from 0 in Ruby.

The illustration below shows how the insert method works in Ruby:

How does the insert method work in Ruby

Syntax

The insert method works on a string or an array in Ruby. We use the . operator to link our string or array with the method. An example is shown below:

"myString".insert(2,"e")

or

Array.insert(2,"e")

Parameters

The insert function takes in two parameters: the index and the element.

The index can be a negative number as well. In that case, the insert method will add an element to the specified index from the end of the string or the array.

-1 refers to the last index of the string or array.

Return value

The insert method returns a modified string or array with the element inserted at the specified index.

String example

The code snippet below shows the insert method applied on a string:

puts "Educative".insert(2, 'u')
puts "Cat".insert(1, 'a')
puts "Work".insert(-1, "m")

Array example

The code snippet below shows the insert method applied on an array:

array1 = [1,2,3,4,5,6]
puts "inserted in array1 : #{array1.insert(2, 10)}"
array2 = [1,2,3,4,5,6]
puts "inserted in array2 : #{array2.insert(-2, 10)}"

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved