Ruby | pop() function

The pop() function in Ruby is used to pop or remove the last element of the given array and returns the removed elements.

Syntax: pop(Elements)

Parameters:
Elements : This is the number of elements which are to be removed from the end of the given array. If this parameter is not used then it removes and returns the single last element of the given array.



Returns: the removed elements.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Initializing some arrays of elements
Array = [1, 2, 3, 4, 5, 6, 7]
  
# Calling pop() function
A = Array.pop 
B = Array.pop(2)
C = Array.pop(3)
D = Array
  
# Printing the removed elements 
puts "#{A}"
puts "#{B}"
puts "#{C}"
  
# Printing the remaining array
puts "#{D}"

chevron_right


Output:

7
[5, 6]
[2, 3, 4]
[1]

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Initializing some arrays of elements
Array = ["a", "b", "c", "d", "e", "f", "g"]
  
# Calling pop() function
A = Array.pop 
B = Array.pop(1)
C = Array.pop(2)
D = Array.pop(3)
E = Array
  
# Printing the removed elements 
puts "#{A}"
puts "#{B}"
puts "#{C}"
puts "#{D}"
  
# Printing the remaining array
puts "#{E}"

chevron_right


Output:

g
["f"]
["d", "e"]
["a", "b", "c"]
[]

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



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.