Jun 02 2008

Using a Stack with Ruby

Published by john at 10:01 pm under Ruby

  
  

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.

Technorati Tags: ,

2 Responses to “Using a Stack with Ruby”

  1. James Branamon 11 Jun 2008 at 6:27 am

    Hi again,
    This would also be a great contribution to NB Comm Docs. Can we use it?

    Thanks,

    –James

  2. johnon 11 Jun 2008 at 6:34 am

    James, you are welcome to share any of the tips you find here. All that I ask is that you make a reference (a link if possible) back to the original tip.

Trackback URI | Comments RSS

Leave a Reply