How to push and pop elements in a queue in Ruby?

RubyServer Side ProgrammingProgramming

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
raja
Updated on 25-Jan-2022 10:55:33

Advertisements