Class: RPN::Stack

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

Defined Under Namespace

Classes: InsufficientValuesAvailable, UnsolvableExpressionError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(arity) ⇒ Stack

Returns a new instance of Stack.



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

def initialize arity
  @arity = arity
  @elements = []
end

Instance Attribute Details

#arityObject (readonly)

Returns the value of attribute arity.



6
7
8
# File 'lib/rpn/stack.rb', line 6

def arity
  @arity
end

#elementsObject (readonly)

Returns the value of attribute elements.



6
7
8
# File 'lib/rpn/stack.rb', line 6

def elements
  @elements
end

Instance Method Details

#clearObject



44
45
46
# File 'lib/rpn/stack.rb', line 44

def clear
  elements.clear
end

#pop(amount) ⇒ Object



36
37
38
# File 'lib/rpn/stack.rb', line 36

def pop amount
  elements.pop amount
end

#push(token) ⇒ Object



32
33
34
# File 'lib/rpn/stack.rb', line 32

def push token
  elements.push token
end

#sizeObject



40
41
42
# File 'lib/rpn/stack.rb', line 40

def size
  elements.size
end

#solve(tokens) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/rpn/stack.rb', line 13

def solve tokens
  clear
  tokens.each do |token|
    if Numeric === token
      push token
      next
    end
    raise InsufficientValuesAvailable\
          .new("Cannot apply #{token} to less than #{arity} values!") if size < arity
    result = pop(arity).inject do |acc, e|
      acc.send(token, e)
    end
    push result
  end
  raise UnsolvableExpressionError\
        .new("The final stack contained more than one value: #{elements.inspect}") if size > 1
  elements.first
end