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
# Ruby program to add elements # in array # creating string using [] str = [ "GFG" , "G4G" , "Sudo" , "Beginner" ] str[ 4 ] = "new_ele" ; print str # in we skip the elements str[ 6 ] = "test" ; |
Output:
["GFG", "G4G", "Sudo", "Beginner", "new_ele"] ["GFG", "G4G", "Sudo", "Beginner", "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" , "Beginner" ] str.push( "w3wiki" ) print str |
Output:
["GFG", "G4G", "Sudo", "Beginner", "w3wiki"]
Method #3: Using << syntax instead of the push method –
Ruby
# Ruby program to add elements # in array # creating string using [] str = [ "GFG" , "G4G" , "Sudo" , "Beginner" ] str << "w3wiki" print str |
Output:
["GFG", "G4G", "Sudo", "Beginner", "w3wiki"]
Method #4: Add element at the beginning –
Ruby
# Ruby program to add elements # in array # creating string using [] str = [ "GFG" , "G4G" , "Sudo" , "Beginner" ] str.unshift( "ele_1" ) print str |
Output:
["ele_1", "GFG", "G4G", "Sudo", "Beginner"]
Contact Us