Class: Arithmetic::Parser
- Inherits:
-
Object
- Object
- Arithmetic::Parser
- Defined in:
- lib/arithmetic/parser.rb
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(exp) ⇒ Parser
constructor
A new instance of Parser.
- #parse ⇒ Object
Constructor Details
#initialize(exp) ⇒ Parser
Returns a new instance of Parser.
8 9 10 11 |
# File 'lib/arithmetic/parser.rb', line 8 def initialize(exp) @expression = exp @node_stack = [] end |
Class Method Details
.is_a_number?(str) ⇒ Boolean
4 5 6 |
# File 'lib/arithmetic/parser.rb', line 4 def self.is_a_number?(str) str.respond_to?(:to_str) && !!str.to_str.match(/^[\d\.]+$/) end |
Instance Method Details
#parse ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/arithmetic/parser.rb', line 13 def parse tokens = Tokenizer.new.tokenize(@expression) op_stack = [] tokens.each do |token| if token.is_a? Operator # clear stack of higher priority operators while (!op_stack.empty? && op_stack.last != "(" && op_stack.last.priority >= token.priority) push_operator(op_stack.pop) end op_stack.push(token) elsif token == "(" op_stack.push(token) elsif token == ")" while op_stack.last != "(" push_operator(op_stack.pop) end # throw away the '(' op_stack.pop else push_operand(token) end end until op_stack.empty? push_operator(op_stack.pop) end parsed_expression = @node_stack.pop raise InvalidExpression.new(@expression) unless @node_stack.empty? parsed_expression end |