Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array
ruby
element
insert
communitycreator

How to add new elements in an array using insert in Ruby

okwudili onyejiaku

Overview

Yes, new items can be added to an already existing array. With the insert() method, this is possible. The insert method takes two parameters. One is the index position to start the insertion and the other is the element to insert.

Another good thing about the insert() method is that you can insert multiple elements at once.

Syntax

array.insert(index, elem1, elem2, ..., elemN)

Parameters

  • index: This is the first parameter. It specifies the index position in the array to start the insertion.

  • elem1, elem2, ..., elemN: This is the element or elements you want to insert into the array. It could be one or more than one.

Return value

The value returned is a new array that contains the original elements and the newly inserted elements.

Code

In the code below, we demonstrate the use of the insert() method.

# create several arrays
arr1 = [1, 2]
arr2 = ["a", "f"]
arr3 = ["FireFox", "Chrome", ]
arr4 = ["Google", "Netflix", "Apple", "Amazon"]

# insert elements to already
# existing arrays using insert()
a = arr1.insert(2, 3)
b = arr2.insert(1, "b", "c", "d", "e")
c = arr3.insert(0, "Opera", "IE")
d = arr4.insert(4, "Meta")

# print the returned values
puts "#{a}"
puts "#{b}"
puts "#{c}"
puts "#{d}"
Using the insert method

In this example, we created several arrays and inserted elements to them using this method. Finally, we printed the returned value to the console.

RELATED TAGS

array
ruby
element
insert
communitycreator
RELATED COURSES

View all Courses

Keep Exploring