How to build Stack in Ruby
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 sci…
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:
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.
Also here is a simple explanation of pop and push:
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
// keep reading

Indie Release Notes #6: MudQuest Reborn
MudQuest Reborn: Enhanced indie game with SwiftUI, new partnerships, and app updates for better performance
read→
Indie Updates: 413 Content Too Large
Struggling to scale down MudQuest project as deadline looms. Refocusing on real-time event finder. Key features outlined for completion
read→
Indie Release Notes #5
Discover MudQuest: the first social media app for off-road enthusiasts to organize and join real-time adventures and trail gatherings
read→