Class: RotationHash

Inherits:
Hash
  • Object
show all
Defined in:
lib/rotation_hash.rb

Overview

A Hash descendant with elements count limit and rotation

Examples:

Create a new RotationHash with the limit

rh = RotationHash.new(3, 'default_value')
rh['one']      = 1
rh['two']      = 2
rh['three']    = 3
rh['whatever'] = '¯\_(ツ)_/¯'

p rh['inexistent'] # => "default_value"
p rh               # => {"two"=>2, "three"=>3, "whatever"=>"¯\_(ツ)_/¯"}

Constant Summary collapse

VERSION =

Current library version

'0.1.0'

Instance Method Summary collapse

Constructor Details

#initialize(rotation_limit, *args) ⇒ RotationHash

Note:

The first argument used to set a limit all the others passed to the Hash as is.

Create a new RotationHash

Parameters:

  • rotation_limit (Integer)

    the max possible elements count

  • args (Array<Object>)

    Any number of Objects to pass to the Hash



25
26
27
28
# File 'lib/rotation_hash.rb', line 25

def initialize(rotation_limit, *args)
  @rotation_limit = rotation_limit
  super(*args)
end

Instance Method Details

#[]=(key, value) ⇒ Object

Overloaded Hash assignment method. Adds elements and on reaching the limit automatically rotates the Hash

Parameters:

  • key (Object)

    the key to assign the value to

  • value (Object)

    the value to set on the key

Returns:

  • (Object)

    the object that was assigned to the key



37
38
39
40
# File 'lib/rotation_hash.rb', line 37

def []=(key, value)
  shift if length + 1 > @rotation_limit
  super(key, value)
end