What is array.pop() in Ruby?

pop() is a Ruby array method that pops or removes the last element of a given array. It permanently removes the last element of an array.

Syntax

array.pop(noOfElements)

Parameter

noOfElements: This is the number of elements to be removed from the end of the array. If it is not specified, only the last element will be removed and returned.

Return Value

The returned value is the element or elements that were removed.

Example

In the example below, we create an array and use the pop() method.

# Initializing some arrays of elements
arr = [1, 2, 3, 4, 5, 6, 7]
# Calling pop() function
A = arr.pop()
B = arr.pop(2)
C = arr.pop(3)
D = arr
# Printing the removed elements
puts "#{A}"
puts "#{B}"
puts "#{C}"
# Printing the remaining array
puts "#{D}"
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources