How to Use the Ruby pop Method

09/22/2021

Contents

In this article, you will learn how to use the Ruby pop method.

Using the pop method

The Ruby pop method is a built-in method that removes the last element from an array and returns it. Here’s how you can use the pop method in your Ruby code:

Syntax
array.pop
Example
array = [1, 2, 3, 4, 5]
last_element = array.pop
puts last_element # prints 5
puts array.inspect # prints [1, 2, 3, 4]

In this example, we first create an array with five elements. Then we call the pop method on the array, which removes the last element from the array and returns it. We assign the returned value to the last_element variable and print it to the console.

Finally, we print the modified array to the console using the inspect method to verify that the last element has been removed.

Modifying the Array

You can also use the pop method to modify the array directly. For example:


In this case, we’re not assigning the return value to a variable. Instead, we’re using the pop method to modify the array directly. When we print the array to the console using inspect, we can see that the last element has been removed.

Handling Empty Arrays

If you call the pop method on an empty array, it will return nil. For example:

empty_array = []
last_element = empty_array.pop
puts last_element.inspect # prints nil
puts empty_array.inspect # prints []

In this case, we create an empty array and call the pop method on it. Since there are no elements in the array, the pop method returns nil. We assign this value to the last_element variable and print it to the console. Finally, we print the modified array to the console using the inspect method to verify that it is still empty.