Class: Lich::Common::LimitedArray

Inherits:
Array
  • Object
show all
Defined in:
lib/common/limitedarray.rb

Overview

A class that extends the functionality of an Array to limit its size. When the maximum size is reached, the oldest elements are removed.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(size = 0, obj = nil) ⇒ LimitedArray

Initializes a new LimitedArray with a specified maximum size.

Examples:

limited_array = Lich::Common::LimitedArray.new(5)

Parameters:

  • size (Integer) (defaults to: 0)

    the initial size of the array (default is 0)

  • obj (Object) (defaults to: nil)

    the object to initialize the array with (default is nil)

Raises:

  • (ArgumentError)

    if size is negative



19
20
21
22
# File 'lib/common/limitedarray.rb', line 19

def initialize(size = 0, obj = nil)
  @max_size = 200
  super
end

Instance Attribute Details

#max_sizeObject

Returns the value of attribute max_size.



9
10
11
# File 'lib/common/limitedarray.rb', line 9

def max_size
  @max_size
end

Instance Method Details

#historyArray

Returns an empty array representing the history of elements.

Examples:

history = limited_array.history

Returns:

  • (Array)

    an empty array



52
53
54
# File 'lib/common/limitedarray.rb', line 52

def history
  Array.new
end

#push(line) ⇒ Object

Note:

This method modifies the array in place.

Adds an element to the end of the array, removing the oldest elements if the maximum size is exceeded.

Examples:

limited_array.push("new item")

Parameters:

  • line (Object)

    the element to be added to the array

Returns:

  • (Object)

    the element that was added



32
33
34
35
# File 'lib/common/limitedarray.rb', line 32

def push(line)
  self.shift while self.length >= @max_size
  super
end

#shove(line) ⇒ Object

An alias for the push method.

Examples:

limited_array.shove("another item")

Parameters:

  • line (Object)

    the element to be added to the array

Returns:

  • (Object)

    the element that was added



43
44
45
# File 'lib/common/limitedarray.rb', line 43

def shove(line)
  push(line)
end