Ruby Tuesday – Array#pop

In today’s Ruby Tuesday we continue from last week’s post on Array#push and cover Array#pop.

Array#pop will remove the last element from an Array, and return that element.

[1, 2, 3, 4, 5].pop
# => 5
[:a, :b, :c, :d, :e].pop
# => :e

By assigning a new array to a variable, and then calling pop on the array, we can see that it does in fact mutate the array, and the last item is no longer there.

stack = [1, 2, 3, 4, 5]
# => [1, 2, 3, 4, 5]
# => 5
# => [1, 2, 3, 4]

Ruby makes the decision to return nil if you call Array#pop on an empty array instead of raising an exception.

# => nil

While being safer as far as not causing an exception, it does introduce some danger, as you can keep calling pop on an empty array and it will keep returning nils

10.times{ empty_array.pop }
=> 10

Another potential way there is some danger, is that if you just use Array#pop by itself, you can’t distinguish between an empty array, and an array with nils.

stack_with_nils = [1, nil, 2, nil]
=> [1, nil, 2, nil]
[14] pry(main)> stack_with_nils.pop
=> nil
[15] pry(main)> stack_with_nils
=> [1, nil, 2]

And unlike Array#push, which returns self, Array#pop returns the element popped, which will not allow you to chain commands like Array#push does.

[:a, :b, :c, :d, :e].pop.pop
# NoMethodError: undefined method `pop' for :e:Symbol
# from (pry):4:in `__pry__'

If you wish to pop multiple items from the end of the array, you can pass in a non-negative integer value to Array#pop. When passing a number of items to remove, Array#pop returns a list, with the earlier items popped off the array at the back of the list, and the most recent items at the front of the array.

[:a, :b, :c, :d, :e].pop 3
# => [:c, :d, :e]
third, second, first = [:a, :b, :c, :d, :e].pop 3
# => [:c, :d, :e]
# => :e
# => :d
# => :c


One thought on “Ruby Tuesday – Array#pop

  1. Pingback: Ruby Tuesday – Array#dropProctor It | Proctor It

Leave a Reply

Your email address will not be published. Required fields are marked *