Class: Snoopit::Register

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/snoopit/register.rb

Overview

Behaves a bit like a CPU register

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(size = 10, data = nil) ⇒ Register

index always points to where the next element will be added



11
12
13
14
15
16
17
18
19
# File 'lib/snoopit/register.rb', line 11

def initialize(size=10, data=nil)
  if data.nil?
    @register = Array.new size
  else
    @register = Array.new size
    cloned = data.clone
    [0...size].each { |i| @register[i] = cloned[i] }
  end
end

Instance Attribute Details

#sizeObject (readonly)

Returns the value of attribute size.



8
9
10
# File 'lib/snoopit/register.rb', line 8

def size
  @size
end

Instance Method Details

#[](index) ⇒ Object



38
39
40
# File 'lib/snoopit/register.rb', line 38

def [](index)
  @register[index]
end

#[]=(index, value) ⇒ Object



42
43
44
# File 'lib/snoopit/register.rb', line 42

def []=(index, value)
  @register[index] = value
end

#as_json(options = nil) ⇒ Object



54
55
56
# File 'lib/snoopit/register.rb', line 54

def as_json(options=nil)
   @register
end

#eachObject



62
63
64
# File 'lib/snoopit/register.rb', line 62

def each
  @register.each { |r| yield r }
end

#lengthObject



50
51
52
# File 'lib/snoopit/register.rb', line 50

def length
  @register.length
end

#shift(object) ⇒ Object Also known as: push_back

pushes one object on to the end of the array and pops one off the front and returns is



29
30
31
32
33
# File 'lib/snoopit/register.rb', line 29

def shift(object)
  return if @register.size == 0
  @register.push object
  @register.slice! 0 unless @register.size == 1
end

#to_json(*a) ⇒ Object



58
59
60
# File 'lib/snoopit/register.rb', line 58

def to_json(*a)
  as_json.to_json(*a)
end

#unshift(object) ⇒ Object Also known as: push_front

pushes one object to the front of the array and pops one off the end and returns is



22
23
24
25
26
# File 'lib/snoopit/register.rb', line 22

def unshift(object)
  return if @register.size == 0
  @register.unshift object
  @register.pop unless @register.size == 1
end