Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?

Easy Queue implementation in Ruby

This put up incorporates some information from the ChatGPT.

You may assume, “Queues aren’t used a lot in Ruby,” and it is true, you do not usually see a queue implementation in Ruby or Rails initiatives. However for me, the time has handed once I cared about whether or not I will use one thing in my profession or not. I simply need to have the data, and I counsel you studying this put up to do the identical, you may by no means know when you are going to want it and I imagine these items are what make an enormous distinction in our profession.

The Queue is a linear and dynamic knowledge construction, following the FIFO (First In, First Out) precept. This implies the primary ingredient to enter is the primary to go away. Consider a line of individuals at a financial institution: the primary one in line will get served first.



Key traits:

Ordered insertion and elimination: Components are added on the finish of the queue and faraway from the start.



Primary operations:

  • Enqueue: Add a component on the finish of the queue, replace the tail reference, and replace the merchandise rely.

  • Dequeue: Take away the ingredient from the start of the queue, replace the pinnacle reference, and replace the merchandise rely.

  • Peek/Entrance: Try the primary ingredient of the queue with out eradicating it.



Utilization

Ideally suited for conditions requiring processing within the order of arrival, resembling useful resource administration in computing or customer support.

Implementation: Might be carried out with arrays or linked lists. The simplicity and effectivity of the Queue make it a well-liked alternative in numerous software program functions.

Queues, like Linked Lists, require a container to carry the information inside the construction, on this case, Nodes.

A traditional instance of utilizing queues in software program growth is managing asynchronous duties or messages. That is particularly widespread in distributed programs and internet functions, the place operations may be deferred and executed exterior the primary stream to keep away from blocking processing.

For instance, in an e-commerce software, when a consumer locations an order, the order affirmation and cost processing is perhaps added to a queue. In the meantime, the consumer will get a direct response that their order has been acquired. Within the background, providers processing funds and updating stock eat these duties from the queue, processing them sequentially.

This permits the applying to deal with demand spikes extra effectively, spreading the workload over time, and guaranteeing that crucial operations are accomplished reliably and so as.



Implementation

This implementation will not be centered on efficiency, however on being simple to grasp.


# One of many smallest knowledge constructions we are able to have,
# a easy Node performing like a container to wrap our knowledge.

class Node
  attr_accessor :worth, :next_value

  def initialize(worth)
    @worth = worth            # Wrapped knowledge
    @next_value = nil         # Reference to subsequent begins nil    
  finish
finish

# The Queue implementation

class Queue
  attr_accessor :size, :head, :tail

  def initialize
    @size = 0
    @head = nil
    @tail = nil
  finish

  def enqueue(worth)
    node = Node.new(worth)  # Create a brand new node
    @size += 1            # Replace the Queue size 

    if @head.nil?           # Test if head is nil
      @head = @tail = node  # Set the brand new node as head and tail
      return                # ends the enqueue
    finish

    @tail.next_value = node # Holding the references
    @tail = node            # Tail receives the brand new node
  finish

  def dequeue
    return nil if head.nil? # Nothing to dequeue

    @size -= 1            # Replace size to -1

    head = @head            # Save present head in a variable
    @head = head.next_value # Replace head to the second merchandise

    # head.next_value = nil # Breaks hyperlink between the outdated head
                            # required in non GC languages

    head.worth              # Return the eliminated worth
  finish

  def peek
    return nil if head.nil? # Checking once more if head is nil

    head.worth              # Returns the pinnacle worth
  finish
finish

# At all times a good suggestion having some automated exams :)

require 'rspec/autorun'

describe '#enqueue / #dequeue / #peek' do
  it 'has the Jose worth' do
    q = Queue.new
    q.enqueue('Jose')
    anticipate(q.peek).to eq('Jose')
    anticipate(q.size).to eq(1)

    q.enqueue('Mary')
    anticipate(q.peek).to eq('Jose')
    anticipate(q.size).to eq(2)

    q.dequeue
    anticipate(q.peek).to eq('Mary')
    anticipate(q.size).to eq(1)
  finish
finish
Enter fullscreen mode

Exit fullscreen mode

Hope you prefer it.

Add a Comment

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?