我正在使用StringScanner进行这样的词法分析:
def next
@scanner.skip(/\s+/)
value,kind=nil,nil
TOKEN_DEF.each{|tok,regex| (kind=tok;break) if @scanner.scan(regex)}
return Token.new(kind,value,@line,@scanner.pos)
end
Run Code Online (Sandbox Code Playgroud)
首先近似,这很好用,除了我不知道现在如何获取@line号。
我已经阅读了文档,begin_of_line在哪里?方法似乎合适,但我无法弄清楚如何使用它。
小智 2
将您正在扫描的文本保留在变量中并使用“count”
我在我的代码中使用以下内容:
def current_line_number; @text[0..@scanner.pos].count("\n") + 1; end
Run Code Online (Sandbox Code Playgroud)