Ruby push()函数
Ruby中的push()函数用于将给定的元素推到给定数组的末尾,并返回带有推送元素的数组本身。
语法: push(Elements)
参数:
Elements : 这些是要添加到给定数组末端的元素。
返回: 推送元素的数组。
例子 1 :
# Initializing some arrays of elements
Array1 = [1, 2, 3, 4]
Array2 = ["a", "b", "c"]
Array3 = ["gfg", "Geeks", "GeeksforGeeks"]
# Calling push() function
A = Array1.push(5, 6, 7)
B = Array2.push("d", "e", "f")
C = Array3.push("Geek")
# Printing the array of pushed element
puts "#{A}"
puts "#{B}"
puts "#{C}"
输出
[1, 2, 3, 4, 5, 6, 7]
["a", "b", "c", "d", "e", "f"]
["gfg", "Geeks", "GeeksforGeeks", "Geek"]
例2 :
# Initializing some arrays of elements
Array1 = [10, 20, 30, 40]
Array2 = ["Z", "Y", "X"]
Array3 = ["ab", "abc", "abcd"]
# Initializing some elements
# which are to be pushed
p = 50, 60
q = "W", "V", "U"
r = "abcde", "abcdef"
# Calling push() function
A = Array1.push(p)
B = Array2.push(q)
C = Array3.push(r)
# Printing the array of pushed element
puts "#{A}"
puts "#{B}"
puts "#{C}"
输出
[10, 20, 30, 40, [50, 60]]
["Z", "Y", "X", ["W", "V", "U"]]
["ab", "abc", "abcd", ["abcde", "abcdef"]]
注意: 在上面的例子中,可以看到,如果我们在一个单独的变量中初始化函数的参数 ,那么它就会在上面显示的数组内给出输出。
参考资料 :https://devdocs.io/ruby~2.5/array#method-i-push