Home »
Ruby Tutorial
Ruby push() function
By IncludeHelp Last updated : December 01, 2024
push() function in Ruby
You may have studied the logic to create the push() function in data structure manually which is used in Stack to push the element to the top of the stack. Likewise, in Ruby, we have a predefined library function known as push(), which is used to add the element or group of elements at the end of the array.
The return type of push() function is an array and it returns an array in which it is invoked along with the pushed elements.
Syntax
push(Element)
Now let us understand the working of push() function with the help of examples.
Example 1
=begin
Ruby program to demonstrate push() function.
=end
# Initializing arrays
Arr1 = [11, 12, 13, 14]
Arr2 = ["x", "y", "z"]
Arr3 = ["Includehelp", "C#", "Ruby"]
Arr4 = ["Kiwi","Banana","Orange","Papaya"]
# Invoking push() function with elements to be added
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}"
Output
[11, 12, 13, 14, 15, 16, 17]
["x", "y", "z", "k", "l", "m"]
["Includehelp", "C#", "Ruby", "Python"]
["Kiwi", "Banana", "Orange", "Papaya", "Grapes"]
Explanation
We have created four arrays. We are invoking push() function with different arrays which are returning the updated array in the corresponding new array. You can see the reflection of all pushed elements in the new array.
If you don't want to create a new array and want to store the new elements in the same Array, then it is also permissible. If you want to push elements in Arr2 then you only have to invoke push function like Arr2.push("k", "l", "m").
Now when will print Arr2, all the pushed elements will be reflected in the array Arr2.
Example 2
=begin
Ruby program to demonstrate push() function.
=end
# Initializing some arrays of elements
Arr1 = [100, 201, 301, 401]
Arr2 = ["KA", "KHA", "GA"]
Arr3 = ["Meera", "Shayama", "Harish"]
# Initializing some elements
# which are to be pushed
num = 501, 601
str = "GHA", "CHA", "PA"
nme = "Radha", "Sabri"
# Calling push() function
A = Arr1.push(num)
B = Arr2.push(str)
C = Arr3.push(nme)
# Printing the array of pushed element
puts "#{A}"
puts "#{B}"
puts "#{C}"
Output
[100, 201, 301, 401, [501, 601]]
["KA", "KHA", "GA", ["GHA", "CHA", "PA"]]
["Meera", "Shayama", "Harish", ["Radha", "Sabri"]]
You can observe in the above code that if we invoke push with variables(which have some values), it creates a 2D array. A 2D array is nothing but an array inside an array.