Method: Unit::System#parse_unit

Defined in:
lib/unit/system.rb

#parse_unit(expr) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/unit/system.rb', line 63

def parse_unit(expr)
  stack, result, implicit_mul = [], [], false
  expr.to_s.scan(TOKENIZER).each do |tok|
    if tok == '('
      stack << '('
      implicit_mul = false
    elsif tok == ')'
      compute(result, stack.pop) while !stack.empty? && stack.last != '('
      raise(SyntaxError, 'Unexpected token )') if stack.empty?
      stack.pop
      implicit_mul = true
    elsif OPERATOR.key?(tok)
      compute(result, stack.pop) while !stack.empty? && stack.last != '(' && OPERATOR[stack.last][1] >= OPERATOR[tok][1]
      stack << OPERATOR[tok][0]
      implicit_mul = false
    else
      val = case tok
            when REAL   then [[:one, tok.to_f, 1]]
            when DEC    then [[:one, tok.to_i, 1]]
            when SYMBOL then symbol_to_unit(tok)
            end
      stack << '*' if implicit_mul
      implicit_mul = true
      result << val
    end
  end
  compute(result, stack.pop) while !stack.empty?
  result.last
end