Last active
January 15, 2025 09:53
-
-
Save icaoberg/2871311 to your computer and use it in GitHub Desktop.
Simple stack in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Author: Ivan E. Cao-Berg ([email protected]) | |
# | |
# Copyright (C) 2012-2025 | |
# School of Computer Science | |
# Carnegie Mellon University | |
# | |
# This program is free software; you can redistribute it and/or modify | |
# it under the terms of the GNU General Public License as published | |
# by the Free Software Foundation; either version 2 of the License, | |
# or (at your option) any later version. | |
# | |
# This program is distributed in the hope that it will be useful, but | |
# WITHOUT ANY WARRANTY; without even the implied warranty of | |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | |
# General Public License for more details. | |
# | |
# You should have received a copy of the GNU General Public License | |
# along with this program; if not, write to the Free Software | |
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA | |
# 02110-1301, USA. | |
# | |
# For additional information visit http://www.andrew.cmu.edu/~icaoberg or | |
# send email to [email protected] | |
class Stack | |
def initialize | |
@stack = [] | |
end | |
# Adds a value to the stack | |
# @param value [Object] the value to be added | |
# @return [Boolean] true if the value is successfully added, false otherwise | |
def push(value) | |
return false if value.nil? | |
@stack.unshift(value) | |
true | |
end | |
# Returns the top value of the stack without removing it | |
# @return [Object, nil] the top value of the stack or nil if the stack is empty | |
def peek | |
@stack.first | |
end | |
# Removes the top value from the stack | |
# @return [Boolean] true if a value was removed, false otherwise | |
def pop | |
[email protected]? | |
end | |
# Returns the number of elements in the stack | |
# @return [Integer] the size of the stack | |
def size | |
@stack.length | |
end | |
# Checks if the stack contains a specific value | |
# @param value [Object] the value to check for | |
# @return [Boolean] true if the value exists, false otherwise | |
def contains?(value) | |
@stack.include?(value) | |
end | |
# Clears all elements from the stack | |
def clear | |
@stack.clear | |
end | |
# Checks if the stack is empty | |
# @return [Boolean] true if the stack is empty, false otherwise | |
def empty? | |
@stack.empty? | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment