How to build Stack in Ruby

Hash tags: Stack Interview Questions

I've decided to resume my algorithm practicing because I simply keep forgetting it and also it's a lot of fun :).

Stack definition from Wiki:

In computer science, a stack is an abstract data type that serves as a collection of elements, with two principal operations:

  • push, which adds an element to the collection, and
  • pop, which removes the most recently added element that was not yet removed.

The order in which elements come off a stack gives rise to its alternative name, LIFO (last in, first out). Additionally, a peek operation may give access to the top without modifying the stack. The name "stack" for this type of structure comes from the analogy to a set of physical items stacked on top of each other, which makes it easy to take an item off the top of the stack, while getting to an item deeper in the stack may require taking off multiple other items first.

So technically you can think about the Stack as a stack of plates

Also here is a simple explanation of pop and push:
Screen Shot 2020-01-22 at 11.20.09 AM.png 75.9 KB

Task:

Create a Stack class statically sized. push and pop should return nil if the stack is overflowing or underflowing respectively. Implement private predicate methods full? and empty? and public method size that returns the length of the stack, and look that returns the value on the top of the stack.

Solution:

class Stack
  def initialize(size)
    @size = size
    @stack = Array.new(@size)
    @top = -1
  end

  def push(element)
    if element.nil? || full?
      puts 'The Stack is full or Element is not provided. Returning nil!'
      nil
    else
      @top +=1
      @stack[@top] = element
      self
    end
  end

  def pop
    if empty?
      puts 'The Stack is empty. Pop method returning nil!'
      nil
    else
      popper = @stack[@top]
      @stack[@top] = nil
      @top -=1
      puts "Taking out #{popper}"
      self
    end
  end

  def size
    @size
  end

  def look
    @stack[@top]
  end

  private
  def empty?
    @top == -1
  end

  def full?
    @top == (size - 1)
  end
end

PROJECTS


MORE BLOGS