ddeveloperr
2/6/2016 - 12:17 AM

Algorithm and Data Structures With Ruby - #5 Stack

Algorithm and Data Structures With Ruby - #5 Stack

#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


=begin

Sample Output :
~/work/ruby_tutorials$ ruby stack.rb
(LeftMost : Oldest Element)  (RightMost : Newest Element)
(LeftMost : Oldest Element) 3<-5<-10 (RightMost : Newest Element)
Popped the value : 10
(LeftMost : Oldest Element) 3<-5 (RightMost : Newest Element)
Popped the value : 5
(LeftMost : Oldest Element) 3 (RightMost : Newest Element)
=end