在 Ruby 中添加数组元素
在本文中,我们将学习如何在 Ruby 中向数组添加元素。
方法#1:使用索引
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";
Ruby
# Ruby program to add elements
# in array
# creating string using []
str = ["GFG", "G4G", "Sudo", "Geeks"]
str.push("Geeksforgeeks")
print str
Ruby
# Ruby program to add elements
# in array
# creating string using []
str = ["GFG", "G4G", "Sudo", "Geeks"]
str << "Geeksforgeeks"
print str
Ruby
# Ruby program to add elements
# in array
# creating string using []
str = ["GFG", "G4G", "Sudo", "Geeks"]
str.unshift("ele_1")
print str
输出:
["GFG", "G4G", "Sudo", "Geeks", "new_ele"]
["GFG", "G4G", "Sudo", "Geeks", "new_ele", nil, "test"]
方法 #2:在下一个可用索引处插入(使用 push() 方法) -
红宝石
# Ruby program to add elements
# in array
# creating string using []
str = ["GFG", "G4G", "Sudo", "Geeks"]
str.push("Geeksforgeeks")
print str
输出:
["GFG", "G4G", "Sudo", "Geeks", "Geeksforgeeks"]
方法 #3:使用<<语法而不是 push 方法 –
红宝石
# Ruby program to add elements
# in array
# creating string using []
str = ["GFG", "G4G", "Sudo", "Geeks"]
str << "Geeksforgeeks"
print str
输出:
["GFG", "G4G", "Sudo", "Geeks", "Geeksforgeeks"]
方法#4:在开头添加元素——
红宝石
# Ruby program to add elements
# in array
# creating string using []
str = ["GFG", "G4G", "Sudo", "Geeks"]
str.unshift("ele_1")
print str
输出:
["ele_1", "GFG", "G4G", "Sudo", "Geeks"]