您可能已经研究了在数据结构中手动创建push()
函数的逻辑,该逻辑在Stack中用于将元素推入堆栈的顶部。同样,在Ruby中,我们有一个称为的预定义库函数push()
,用于在数组末尾添加元素或元素组。
push()
函数的返回类型是一个数组,它返回一个数组,在该数组中它与推入的元素一起被调用。
语法:
push(Element)
现在,让我们借助示例来了解push()
函数的工作原理。
范例1:
=begin Ruby program to demonstrate push() function. =end # Initializing arrays Arr1 = [11, 12, 13, 14] Arr2 = ["x", "y", "z"] Arr3 = ["nhooo", "C#", "Ruby"] Arr4 = ["Kiwi","Banana","Orange","Papaya"] #调用带有添加元素的push()函数 Arr1push = Arr1.push(15, 16, 17) Arr2push = Arr2.push("k", "l", "m") Arr3push = Arr3.push("Python") Arr4push = Arr4.push("Grapes") # Printing the array of pushed element puts "#{Arr1push}" puts "#{Arr2push}" puts "#{Arr3push}" puts "#{Arr4push}"
输出结果
[11, 12, 13, 14, 15, 16, 17] ["x", "y", "z", "k", "l", "m"] ["nhooo", "C#", "Ruby", "Python"] ["Kiwi", "Banana", "Orange", "Papaya", "Grapes"]
代码逻辑:
我们创建了四个数组。我们正在调用具有不同数组的push()
函数,这些数组将在对应的新数组中返回更新后的数组。您可以看到新数组中所有推送元素的反射。
如果您不想创建一个新数组并将新元素存储在同一数组中,那么它也是允许的。如果要在Arr2中推送元素,则只需调用类似Arr2.push(“ k”,“ l”,“ m”)的推送函数。
现在,当将打印Arr2时,所有压入的元素将反映在数组Arr2中。
范例2:
=begin Ruby program to demonstrate push() function. =end #初始化一些元素数组 Arr1 = [100, 201, 301, 401] Arr2 = ["KA", "KHA", "GA"] Arr3 = ["Meera", "Shayama", "Harish"] #初始化一些元素 #哪些是要推的 num = 501, 601 str = "GHA", "CHA", "PA" nme = "Radha", "Sabri" #调用push()函数 A = Arr1.push(num) B = Arr2.push(str) C = Arr3.push(nme) #打印推送元素数组 puts "#{A}" puts "#{B}" puts "#{C}"
输出结果
[100, 201, 301, 401, [501, 601]] ["KA", "KHA", "GA", ["GHA", "CHA", "PA"]] ["Meera", "Shayama", "Harish", ["Radha", "Sabri"]]
您可以在上面的代码中观察到,如果我们使用调用push variables(which have some values)
,它将创建一个2D数组。2D数组不过是数组内部的数组。