Class: SpaghettiStack

Inherits:
Object
  • Object
show all
Defined in:
lib/spaghetti_stack.rb,
lib/spaghetti_stack/version.rb

Defined Under Namespace

Classes: Node

Constant Summary collapse

VERSION =
"0.2.1"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ SpaghettiStack

Returns a new instance of SpaghettiStack.



23
24
25
26
# File 'lib/spaghetti_stack.rb', line 23

def initialize(data)
  @root = Node.new(data)
  @top = root
end

Instance Attribute Details

#rootObject (readonly)

Returns the value of attribute root.



21
22
23
# File 'lib/spaghetti_stack.rb', line 21

def root
  @root
end

#topObject (readonly)

Returns the value of attribute top.



21
22
23
# File 'lib/spaghetti_stack.rb', line 21

def top
  @top
end

Instance Method Details

#each {|node| ... } ⇒ Object

Yields:

  • (node)


49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/spaghetti_stack.rb', line 49

def each
  return self.to_enum unless block_given?

  node = top
  until node == root
    yield node
    node = node.parent
  end
  yield node

  visited_nodes.each { |visited_node| yield visited_node }

  self
end

#inspectObject



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/spaghetti_stack.rb', line 64

def inspect
  output = ""

  each do |node|
    data = node.data

    if node == root
      output = "(#{data}#{output})"
      return output
    else
      output = " <~ #{data}" + output
    end
  end

  super
end

#popObject



35
36
37
38
39
40
41
42
43
# File 'lib/spaghetti_stack.rb', line 35

def pop
  node   = top
  parent = node.parent

  if parent
    @top = parent
    visited_nodes << node
  end
end

#push(data) ⇒ Object Also known as: <<



28
29
30
31
# File 'lib/spaghetti_stack.rb', line 28

def push(data)
  node = Node.new(data, top)
  @top = node
end

#visited_nodesObject



45
46
47
# File 'lib/spaghetti_stack.rb', line 45

def visited_nodes
  @visited_nodes ||= []
end