Class: Canned::InmmutableStack

Inherits:
Object
  • Object
show all
Defined in:
lib/canned/stack.rb

Overview

Implements an inmmutable stack where every operation generates a new stack

Used by the test contexts to hold the subject stack.

Defined Under Namespace

Classes: Entry, NotFound

Instance Method Summary collapse

Constructor Details

#initialize(_entry = nil, _tail = nil) ⇒ InmmutableStack

Returns a new instance of InmmutableStack.



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

def initialize(_entry=nil, _tail=nil)
  @stack = if _tail then _tail.entries else [] end
  @stack << _entry if _entry
end

Instance Method Details

#empty?Boolean

Returns true if stack is empty

Returns:

  • (Boolean)


35
# File 'lib/canned/stack.rb', line 35

def empty?; @stack.empty?; end

#entriesObject

 Gets a copy of the internal stack state.



32
# File 'lib/canned/stack.rb', line 32

def entries; @stack.clone; end

#push(_tag, _name, _value) ⇒ Object

 Creates a new stack using the current stack as tail.



39
40
41
# File 'lib/canned/stack.rb', line 39

def push(_tag, _name, _value)
  InmmutableStack.new Entry.new(_tag, _name, _value), self
end

#resolve(_name) ⇒ Object

 Resolves a stack value by it’s name

Raises:



55
56
57
58
59
60
61
# File 'lib/canned/stack.rb', line 55

def resolve(_name)
  _name = _name.to_s
  @stack.reverse_each do |item|
    return item.obj if item.name == _name
  end
  raise NotFound
end

#top(_tag = nil) ⇒ Object

Retrieves the top value of the stack



45
46
47
48
49
50
51
# File 'lib/canned/stack.rb', line 45

def top(_tag=nil)
  return @stack.last.obj if _tag.nil?
  @stack.reverse_each do |item|
    return item.obj if item.tag == _tag
  end
  return nil
end