How to Use a Stack Data Structure in Ruby

Oct
3

After more tinkering in Ruby, I came across the need to use the Stack data structure. To my surprise, one was nowhere to be found. However, I was even more surprised when I found out that the Stack operations are implemented by the standard Ruby Array class.

# initialization
stack = Array.new

# pushing an item onto the stack
stack.push("item")
stack << "item2"

# popping an item off the stack
top_item = stack.pop

# peeking at the top item
puts stack.last
puts stack[-1]

# checking if the stack is empty
puts stack.empty?

# checking the size of the stack
puts stack.size
puts stack.count
puts stack.length
Tags: #Ruby Author: Seth Westphal
comments powered by Disqus