Skip to content

Instantly share code, notes, and snippets.

@icaoberg
Last active January 15, 2025 09:55
Show Gist options
  • Save icaoberg/2871344 to your computer and use it in GitHub Desktop.
Save icaoberg/2871344 to your computer and use it in GitHub Desktop.
Simple queue in Ruby
# 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 Queue
def initialize
@queue = []
end
# Adds a value to the queue
# @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?
@queue.push(value)
true
end
# Returns the last value in the queue without removing it
# @return [Object, nil] the last value in the queue or nil if the queue is empty
def peek
@queue.last
end
# Removes and returns the last value from the queue
# @return [Boolean] true if a value was removed, false otherwise
def pop
[email protected]?
end
# Returns the number of elements in the queue
# @return [Integer] the size of the queue
def size
@queue.length
end
# Checks if the queue contains a specific value
# @param value [Object] the value to check for
# @return [Boolean] true if the value exists, false otherwise
def contains?(value)
@queue.include?(value)
end
# Clears all elements from the queue
def clear
@queue.clear
end
# Checks if the queue is empty
# @return [Boolean] true if the queue is empty, false otherwise
def empty?
@queue.empty?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment