When I write a Ruby program, arrays end up being used as my go-to datatype consistently. Maybe I am not very advanced and have a 1-dimensional programming technique — I think about this, and its possible because I am not an expert. However, the more time goes on the more I am reassured that the Ruby Array truly is an incredibly simple but flexible datatype that can be used in wide array of applications. One such use of Ruby arrays that I find myself using often is using Ruby arrays as a kind of stack within my scripts.
Ruby Arrays as your Temporary Stack
For example, often in programs we want to have a ‘stack‘. Meaning we have some temporary place where we need to store items and then later retrieve them from that temporary storage place. For me, the Ruby array is an incredibly easy way to implement this behavior.
The primary methods you will be using are pop and push. Push adds a variable to the end of an array. While pop removes the last item in the array and returns it. This is an important distinction – push appends a new entry to the end of an array and returns the newly formed array, leaving the item being pushed unaffected. On the otherhand, pop returns the last item from the array being targetted but also leaves the array with that last item now gone.
Here are examples of using Pop and Push:
The standard format for Push is:
The standard format for Pop is:
var = array.pop
Here is a super basic example of how to implement the stack behavior using Ruby arrays:
temp_stack = Array
i = 0
until i > 9
i += 1
The array temp_stack would contain the following after this code:
temp_stack = ['0','1','2','3','4','5','6','7','8','9']
Now, imagine we add this to the prior code
for entry in temp_stack
temp_num = temp_stack.pop
When executed, this code would print out the following:
Of course, we don’t need to use pop in order to access those array items, but I did so I could show what the puts would output. In the real world, instead of just printing the entry in the array we would maybe run another function on it – or push it to a DB or something.
In the above code I also used some of the other reasons why I think Ruby arrays are so great. For instance, in the above for loop you see that you can enumerate over an array within a block. As we know, with Ruby blocks – we have instance variables that are essentially anonymous functions since they only exist within the for loop. This is a really cool ability.