我在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這是一種功能性與非功能性的方法,真的。 –