Using a Stack with Ruby

Mon, Jun 2

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.

4 comments

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

Thanks,

–James

by James Branam on Jun 11, 2008. Reply #

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.

by john on Jun 11, 2008. Reply #

Hi,

if you return self in “push” and “pop” like
def push(item)
@the_stack.push item
return self
end
you can do interesting things like

stack.push(3).push(5)

and test stack laws like

stack.push(3).pop() == stack

OK, for the latter equality you also need an equals-method for the stack class.
By the way, do you see a “correct” way to restrict stacks to certain data types, like e.g. in Java: Stack?

klaus

by klaus on Sep 10, 2009. Reply #

Greetings,

Since the method in the Stack class are all offered by nature Array class in ruby standard lib, why would we need to implement a “Stack”? Maybe Array.new() is already a full-functioned stack =)

by tpy on Oct 2, 2011. Reply #

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>