我在Ruby中编写了一个编译器,并且我有许多实例方法将修改实例变量的类。例如,我的词法分析器(即在代码中发现的标记部分),工作原理是这样的:应该在Ruby中修改实例变量吗?
class Lexer
attr_accessor :tokens
def initialize(input)
@input = input
@tokens = nil
end
def lex!
# lex through the input...
# @tokens << { lexeme: 'if', kind: :if_statement }
@tokens
end
end
lexer = Lexer.new('if this then that')
lexer.lex! # => [ { lexeme: 'if', kind: :if_statement }, ... ]
lexer.tokens # => [ { lexeme: 'if', kind: :if_statement }, ... ]
这是一个有效的做法呢?或者,我是否应该使用方法(如#lex
)接受输入并返回结果,而不修改实例变量?
class Lexer
def initialize
end
def lex(input)
# lex through the input...
# tokens << { lexeme: 'if', kind: :if_statement }
tokens
end
end
lexer = Lexer.new
lexer.lex('if this then that') # => [ { lexeme: 'if', kind: :if_statement }, ... ]
不,它不会用'@ tokens'做任何事情。我认为这几乎可以回答我的问题,谢谢! –
@EthanTurkeltaub \t这是一种功能性与非功能性的方法,真的。 –