Add array elements in Ruby

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

Method #1: Using Index

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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) –

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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

Method #4: Add element at the beginning –

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.