Open In App

Add array elements in Ruby

Last Updated : 20 Jul, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to add elements to an array in Ruby.
Method #1: Using Index 

Ruby




# Ruby program to add elements 
# in array
   
# creating string using []
str = ["GFG", "G4G", "Sudo", "Geeks"]
   
str[4] = "new_ele";
print str
 
# in we skip the elements
str[6] = "test";


Output:

["GFG", "G4G", "Sudo", "Geeks", "new_ele"]

["GFG", "G4G", "Sudo", "Geeks", "new_ele", nil, "test"]

Method #2: Insert at next available index (using push() method) –

Ruby




# Ruby program to add elements 
# in array
   
# creating string using []
str = ["GFG", "G4G", "Sudo", "Geeks"]
   
str.push("Geeksforgeeks")
print str


Output:

 ["GFG", "G4G", "Sudo", "Geeks", "Geeksforgeeks"] 

Method #3: Using << syntax instead of the push method – 

Ruby




# Ruby program to add elements 
# in array
   
# creating string using []
str = ["GFG", "G4G", "Sudo", "Geeks"]
   
str << "Geeksforgeeks"
print str


Output:

 ["GFG", "G4G", "Sudo", "Geeks", "Geeksforgeeks"] 

Method #4: Add element at the beginning –  

Ruby




# Ruby program to add elements 
# in array
   
# creating string using []
str = ["GFG", "G4G", "Sudo", "Geeks"]
   
str.unshift("ele_1")
print str


Output:

 ["ele_1", "GFG", "G4G", "Sudo", "Geeks"] 

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads