How to Implement Stack in Ruby: Simple Guide with Examples
In Ruby, you can implement a
stack using an array with push and pop methods to add and remove elements. Alternatively, create a custom Stack class that encapsulates these operations for clearer code and better control.Syntax
A stack in Ruby can be implemented using an array with these main methods:
push(element): Adds an element to the top of the stack.pop: Removes and returns the top element from the stack.peekorlast: Returns the top element without removing it.
Alternatively, you can define a Stack class with these methods to organize stack behavior.
ruby
class Stack def initialize @elements = [] end def push(element) @elements.push(element) end def pop @elements.pop end def peek @elements.last end def empty? @elements.empty? end end
Example
This example shows how to use the Stack class to add, remove, and check elements in the stack.
ruby
class Stack def initialize @elements = [] end def push(element) @elements.push(element) end def pop @elements.pop end def peek @elements.last end def empty? @elements.empty? end end stack = Stack.new stack.push(10) stack.push(20) stack.push(30) puts "Top element: #{stack.peek}" puts "Removed element: #{stack.pop}" puts "Top element after pop: #{stack.peek}" puts "Is stack empty? #{stack.empty?}"
Output
Top element: 30
Removed element: 30
Top element after pop: 20
Is stack empty? false
Common Pitfalls
Common mistakes when implementing a stack in Ruby include:
- Using
shiftinstead ofpop, which removes from the front, not the top. - Not checking if the stack is empty before popping, which can cause errors.
- Modifying the internal array directly from outside the class, breaking encapsulation.
Always use pop to remove the top element and check empty? before popping.
ruby
stack = [] # Wrong: removes first element, not top stack.push(1) stack.push(2) stack.shift # removes 1, not 2 # Right: stack.push(1) stack.push(2) stack.pop # removes 2 # Check empty before pop stack = [] if !stack.empty? stack.pop else puts "Stack is empty, cannot pop" end
Output
Stack is empty, cannot pop
Quick Reference
Stack operations in Ruby using arrays:
| Operation | Method | Description |
|---|---|---|
| Add element | push(element) | Adds element to the top of the stack |
| Remove element | pop | Removes and returns the top element |
| View top | last or peek | Returns the top element without removing |
| Check empty | empty? | Returns true if stack has no elements |
Key Takeaways
Use Ruby arrays with push and pop to implement a stack easily.
Encapsulate stack behavior in a class for cleaner and safer code.
Always check if the stack is empty before popping to avoid errors.
Avoid using shift as it removes from the bottom, not the top.
Use peek (last) to see the top element without removing it.