Skip to content
Related Articles

Related Articles

Improve Article
Add array elements in Ruby
  • Last Updated : 24 Oct, 2019

In this article, we will learn how to add elements to an array in Ruby.

Method #1: Using Index




# 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() methhod) –




# 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 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 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"] 



My Personal Notes arrow_drop_up
Recommended Articles
Page :