- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to push and pop elements in a queue in Ruby?
In this article, we will learn how to push (insert) and pop (remove) elements in a queue in Ruby.
In Ruby, we can insert elements into a queue with the help of the push function. The syntax of the push function is shown below.
queueName.push(element)
Notice that the above syntax accepts one argument, which is the element that you want to insert into the queue. The result of the above command is that a new element will be added into the front of the queue.
To remove an element from the queue, we can make use of the pop function. The syntax of the pop function is shown below.
queueName.pop()
Notice that the above syntax doesn't accept any argument and the result of the above command is that one element will be removed from the front of the queue.
Now let's take a couple of examples to demonstrate how to utilize these functions.
Example 1
# push() and pop() function in Queue # Create a new QUEUE queueOne queueOne = Queue.new # push 11 queueOne.push(11) # push 22 queueOne.push(22) # pop top element puts queueOne.pop puts queueOne.pop
Output
11 22
Example 2
# pop() and push() function in Queue # Create a new QUEUE queueOne queueOne = Queue.new # push 11 queueOne.push(11) # push 15 queueOne.push(15) # Print element puts queueOne.pop # Again pushes 17 queueOne.push(17) # Print element puts queueOne.pop # Print element puts queueOne.pop
Output
11 15 17