Ruby | push() function

The push() function in Ruby is used to push the given element at the end of the given array and returns the array itself with the pushed elements.

Syntax: push(Elements)

Parameters:
Elements : These are the elements which are to be added at the end of the given array.



Returns: the array of pushed element.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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}"

chevron_right


Output:

[1, 2, 3, 4, 5, 6, 7]
["a", "b", "c", "d", "e", "f"]
["gfg", "Geeks", "GeeksforGeeks", "Geek"]

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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}"

chevron_right


Output:

[10, 20, 30, 40, [50, 60]]
["Z", "Y", "X", ["W", "V", "U"]]
["ab", "abc", "abcd", ["abcde", "abcdef"]]

Note: In the above example, it can be seen that if we initialize the parameters
of the function in a separate variable then it gives output as an array inside the array shown above.

Reference: https://devdocs.io/ruby~2.5/array#method-i-push



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.