stack

Although an array within Ruby supports all the operations you need for working with a stack (push, pop, etc), the problem is, Ruby does not offer a “formal” stack object and therefore the flexibility of the Ruby array can present problems. For instance, even if you intend to treat an array as a stack, nothing will stop you (or another developer using your code) from inserting or deleting anywhere within the stack.

We can work around this by creating a simple Stack class as follows:

class Stack

  def initialize
   @the_stack = []
  end

  def push(item)
    @the_stack.push item
  end

  def pop
    @the_stack.pop
  end

  def count
    @the_stack.length
  end
end

Here is how you might use the stack:

  stack = Stack.new
  stack.push('abc')
  stack.push(100)
  stack.count
  stack.pop()

If need be, you could also add a few convenience methods such as clearing the stack or looking at the last element (without popping it off the stack):

  def clear
    @the_stack.clear
  end

  def look
    @the_stack.last
  end

Give this a try if you need to work with an array as a stack and want to play within the rules of how a stack is implemented as a traditional data structure.