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 = []

  def push(item)
    @the_stack.push item

  def pop

  def count

Here is how you might use the stack:

  stack =

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

  def look

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.


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



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 #


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


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?


by klaus on Sep 10, 2009. Reply #


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 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>