Method: Unit::System#parse_unit

Defined in:
lib/unit/system.rb

#parse_unit(expr) ⇒ Object



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/unit/system.rb', line 81

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