Add array elements in Ruby
In this article, we will learn how to add elements to an array in Ruby.
Method #1: Using Index
Ruby
str = [ "GFG" , "G4G" , "Sudo" , "Geeks" ]
str[ 4 ] = "new_ele" ;
print str
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
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
str = [ "GFG" , "G4G" , "Sudo" , "Geeks" ]
str << "Geeksforgeeks"
print str
|
Output:
["GFG", "G4G", "Sudo", "Geeks", "Geeksforgeeks"]
Method #4: Add element at the beginning –
Ruby
str = [ "GFG" , "G4G" , "Sudo" , "Geeks" ]
str.unshift( "ele_1" )
print str
|
Output:
["ele_1", "GFG", "G4G", "Sudo", "Geeks"]
Last Updated :
20 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...