Class: Utils::Grepper::Queue

Inherits:
Object
  • Object
show all
Defined in:
lib/utils/grepper.rb

Overview

A queue implementation with size limitation.

“item2” # … queue.data # => [ “item1”, “item2”, … ]

The Queue class provides a fixed-size buffer for storing objects. When the maximum size is exceeded, the oldest item is automatically removed.

Examples:

queue = Utils::Grepper::Queue.new(5) queue << “item1” queue <<


Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(max_size) ⇒ Queue

The initialize method sets up a new instance with the specified maximum size and empty data array.

Parameters:

  • max_size (Integer)

    the maximum size limit for the data storage



30
31
32
# File 'lib/utils/grepper.rb', line 30

def initialize(max_size)
  @max_size, @data = max_size, []
end

Instance Attribute Details

#max_sizeInteger (readonly)

The max_size reader method provides access to the maximum size value.

Returns:

  • (Integer)

    the maximum size value stored in the instance



37
38
39
# File 'lib/utils/grepper.rb', line 37

def max_size
  @max_size
end

Instance Method Details

#dataArray

The data method returns a duplicate of the internal data array.

This method provides access to the internal @data instance variable by returning a shallow copy of the array, ensuring that external modifications do not affect the original data structure.

Returns:

  • (Array)

    a duplicate of the internal data array



46
47
48
# File 'lib/utils/grepper.rb', line 46

def data
  @data.dup
end

#push(x) ⇒ Queue Also known as: <<

The push method adds an element to the queue and removes the oldest element if the maximum size is exceeded.

Parameters:

  • x (Object)

    the element to be added to the queue

Returns:

  • (Queue)

    returns self to allow for method chaining



56
57
58
59
60
# File 'lib/utils/grepper.rb', line 56

def push(x)
  @data.shift if @data.size > @max_size
  @data << x
  self
end