Push and Pop method in Ruby
In this lesson, we are going to learn more about arrays, more ways to
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.
Ruby: Push operation
Another way to add or to push item into an array is using
Now, you can see that there are three items in array named
Ruby: Pop operation
To remove the element from an array, we use
For removing the element, you don't need to specify the parameters. It removes the recently inserted item, no matter what it is.
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.
push - to insert item or element into an array.
pop - to remove an item or an element from an array.