Ruby array pop method
In ruby programming language array pop method are used to remove last element of array. This method are returning remove element or nil when array empty. This method is returning removed element. In case array is empty, then they are returns nil value.
The parameter of this inbuilt method is optional, but it is able to take parameter values that indicate the number of elements to be removed from the end of the array. The syntax as follows.
# Remove last element
arr.pop()
# or
arr.pop
# To remove one and more than one element
arr.pop(n) # n indicates number of element
Generally the first method is most commonly used, in the second case when removing more than one element and the array elements are less than the removed element then this method removes all existing elements of the array.
Ruby pop method example
Let us look at some useful examples to understand the functionality of this method. In the first example, the last element from the array is to be removed.
# our array
arr = [1,4,2,3]
# Display array element
print("Before Remove ")
print("\nArray : ",arr)
# pop element
data = arr.pop() # remove single element
# Display array element
print("\nAfter remove : ",data)
print("\nArray : ",arr)

Before Remove
Array : [1, 4, 2, 3]
After remove : 3
Array : [1, 4, 2]
In the second example, see how to extract more than one element in the final state. It is the same as before but in this case the parameter value is used.
# Our array
arr = [6,1,4,2,3]
# Display array element
print(" Before Remove ")
print("\n Array : ",arr)
# pop element
data = arr.pop(3) # remove last 3 element
# Display array element
print("\n Remove ",3," element : ",data)
print("\n After Remove : ",arr)

Before Remove
Array : [6, 1, 4, 2, 3]
Remove 3 element : [4, 2, 3]
After Remove : [6, 1]
When the pop() method removes more than one element, it returns an array that contains the removed elements.
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment