Class: Nudge::Stack

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

Overview

Nudge Stacks are Arrays with some added convenience functions.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ Stack

Stack name must be a symbol

Raises:

  • (ArgumentError)


12
13
14
15
16
# File 'lib/interpreter/stack.rb', line 12

def initialize(name)
  raise(ArgumentError,"Stack name must be a Symbol") if !name.kind_of?(Symbol)
  @name = name
  @entries = []
end

Instance Attribute Details

#entriesObject

Returns the value of attribute entries.



8
9
10
# File 'lib/interpreter/stack.rb', line 8

def entries
  @entries
end

#nameObject (readonly)

Returns the value of attribute name.



9
10
11
# File 'lib/interpreter/stack.rb', line 9

def name
  @name
end

Instance Method Details

#depthObject

Stack#depth returns the number of items



34
35
36
# File 'lib/interpreter/stack.rb', line 34

def depth
  @entries.length
end

#inspectObject



38
39
40
41
42
43
# File 'lib/interpreter/stack.rb', line 38

def inspect
  result = @entries.reverse.inject("[") do |return_string, item|
    return_string << "\n«#{item.type}» #{item.value},"
  end
  result.chop+"]"
end

#peekObject

Reference to the last item pushed to the Stack. Doesn’t remove it



29
30
31
# File 'lib/interpreter/stack.rb', line 29

def peek
  return @entries.last
end

#popObject

Removes the last item pushed to the Stack and returns it



24
25
26
# File 'lib/interpreter/stack.rb', line 24

def pop
  return @entries.pop
end

#push(item) ⇒ Object

Only non-nil objects can be pushed; there is no type checking or validation beyond that.



19
20
21
# File 'lib/interpreter/stack.rb', line 19

def push(item)
  @entries.push(item) unless item == nil
end