Class: Crapshoot::Evaluator

Inherits:
Object
  • Object
show all
Defined in:
lib/crapshoot/evaluator.rb

Overview

Stack-based calculator that relies on the “eval” method of tokens.

Instance Method Summary collapse

Instance Method Details

#evaluate(tokens) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
# File 'lib/crapshoot/evaluator.rb', line 4

def evaluate(tokens)
  @stack = []
  @tokens = tokens.dup
  until @tokens.empty?
    step
  end

  raise "Stack has too many entries: #{@stack.inspect}" unless @stack.length == 1

  return @stack[0]
end

#stepObject



16
17
18
19
20
# File 'lib/crapshoot/evaluator.rb', line 16

def step
  candidate = @tokens.shift
  result = candidate.eval @stack
  @stack.push result
end