Class: Calculator::Lexer

Inherits:
Object
  • Object
show all
Defined in:
lib/linmeric/Calculator.rb

Overview

This lexser creates the tokens splitting the input string according to the operators (OP => see Calculator ) or brackets it returns nil if an unaccepted char (non-number or non-OP or non-bracket) is found

Author

Massimiliano Dal Mas ([email protected])

License

Distributed under MIT license

Instance Method Summary collapse

Instance Method Details

#tokenize(string) ⇒ Object

It creates the tokens according to ‘OP` or ’(‘ and ’)‘

  • argument: the string that needs to be tokenized

  • returns: array of tokens if all the chars are correct; nil else



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/linmeric/Calculator.rb', line 65

def tokenize(string)
  stream = []
  temp   = ""
  for i in 0...string.size
    if OP.include? string[i] or ["(",")"].include? string[i] then
      stream << Token.new(temp) unless temp == ""
      stream << Token.new(string[i])
      temp = ""
    elsif string[i].number? then
      temp += string[i]
    else
      return nil
    end
  end
  stream << Token.new(temp) unless temp == ""
  return stream
end