Ruby doesn't provide an explicit 'stack' but for all practical purposes, the Array provided by Ruby can be treated as a full-fledged stack.
# Based on the ideas from : http://macdevelopertips.com/ruby/using-a-stack-with-ruby.html # Stacks are a Last In First Out Data Structure class Stack def initialize @elements = [] end def length @elements.length end
# Return self def push(x) @elements.push x self end def pop @elements.pop end def peek @elements[-1] end
def display puts"(LeftMost : Oldest Element) "+@elements.join("<-")+" (RightMost : Newest Element)" end end
testStack = Stack.new() # Display initial (empty stack) testStack.display testStack.push(3).push(5).push(10) # Now display stack testStack.display # Check the value at the top of the head popped = testStack.pop puts"Popped the value : "+ popped.to_s # Now the stack is ... testStack.display popped = testStack.pop puts"Popped the value : "+ popped.to_s # Now the stack is ... testStack.display