Push and Pop

In this lesson, we are going to learn more about arrays, more ways to add and remove element to and from arrays. Open Interactive ruby shell and type in :

sample = [ ]

This creates an empty array with no element(s) in it. Now, we are going to add elements to this empty array named sample. You can push the element into an array. You can do that in couple of ways.

sample << 'first item'

This statement pushes the string 'first item' into array.


Push operation

Another way to add or to push item into an array is using push() method.

sample.push("second item")

Push function in Ruby

Push function in Ruby

Now, you can see that there are three items in array named sample.

Push example in Ruby


Pop operation

To remove the element from an array, we use pop() method.

sample.pop

For removing the element, you don’t need to specify the parameters. It removes the recently inserted item, no matter what it is.

Pop function in Ruby

Pop operation

Pop function in Ruby


As you can see, the pop operation removed the recently inserted item hakuna matata and then second item. Now, the array contains only one item. These operations allow arrays to be used as STACK data structure.

Remember,

  1. push - to insert item or element into an array.
  2. pop - to remove an item or an element from an array.